gpt4 book ai didi

Java SimpleDateFormat 将日期递减一天

转载 作者:行者123 更新时间:2023-12-01 18:17:19 25 4
gpt4 key购买 nike

我正在尝试使用 sdf 重新格式化日期字符串。 SDF 正在将日期减少一天。指针会很有帮助。

java版本“1.8.0_31”输入:ChangeDateStringFormat("10-Mar-2015");

代码:

public static String ChangeDateStringFormat (String Input) throws InterruptedException 
{
System.out.print("Input Date inside ChangeDateStringFormat : " + Input );

SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("MST"));

System.out.print(" || Output Date inside ChangeDateStringFormat : " + sdf.format(new Date(Input)) + "\n");
return sdf.format(new Date(Input));
}

实际输出:

在 ChangeDateStringFormat 中输入日期:10-Mar-2015 || ChangeDateStringFormat 内的输出日期:Mar-09-2015

我期望的输出:

在 ChangeDateStringFormat 中输入日期:10-Mar-2015 || ChangeDateStringFormat 内的输出日期:Mar-10-2015

最佳答案

这就是问题:

new Date(Input)

您不应该使用它。相反,构造一个 SimpleDateFormat 来解析您的输入:

import java.text.*;
import java.util.*;

public class Test {
public static void main(String[] args) throws ParseException {
System.out.println(convertDateFormat("10-Mar-2015"));
}

public static String convertDateFormat(String input) throws ParseException {
TimeZone zone = TimeZone.getTimeZone("MST");
SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
inputFormat.setTimeZone(zone);
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy", Locale.US);
outputFormat.setTimeZone(zone);

Date date = inputFormat.parse(input);
return outputFormat.format(date);
}
}

但是:

  • 如果您只是解析日期,则最好指定 UTC 作为时区;您不想因为时区在午夜切换夏令时而遇到问题
  • 如果您要在 Java 8 或更低版本上运行此代码,我强烈建议使用 java.time 而不是 DateCalendar 等等

关于Java SimpleDateFormat 将日期递减一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28857099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com