我正在尝试使用sdf重新格式化日期字符串。SDF正在将日期缩短一天。指针会有帮助的。
java版本"1.8.0_31“输入:ChangeDateStringFormat(”10-2015年3月“);
代码:
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-3月-2015年
我期待的产出:
ChangeDateStringFormat内部输入日期:10-2015年3月-2015年
发布于 2015-03-04 14:40:52
这就是问题所在:
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);
}
}
然而:
java.time
而不是Date
、Calendar
等。https://stackoverflow.com/questions/28857099
复制相似问题