gpt4 book ai didi

java.util.Date格式转换yyyy-mm-dd到mm-dd-yyyy

转载 作者:IT老高 更新时间:2023-10-28 13:51:46 27 4
gpt4 key购买 nike

我有一个 java.util.Date,格式为 yyyy-mm-dd。我希望它采用 mm-dd-yyyy

格式

以下是我尝试进行此转换的示例实用程序:

// Setting the pattern
SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");
// myDate is the java.util.Date in yyyy-mm-dd format
// Converting it into String using formatter
String strDate = sm.format(myDate);
//Converting the String back to java.util.Date
Date dt = sm.parse(strDate);

我得到的输出仍然不是 mm-dd-yyyy 格式。

请告诉我如何将 java.util.Dateyyyy-mm-dd 格式化为 mm-dd-yyyy

最佳答案

Date 是一个容器,用于表示自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来的毫秒数。

它没有格式的概念。

Java 8+

LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);

输出...

05-11-2018
2018-05-11
2018-05-11T17:24:42.980

Java 7-

您应该使用 ThreeTen Backport

原答案

例如...

Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);

输出...

Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013

没有任何格式更改基础 Date 值。这就是 DateFormatters

的目的

更新了更多示例

以防万一第一个例子没有意义......

此示例使用两个格式化程序来格式化相同的日期。然后我使用这些相同的格式化程序将 String 值解析回 Dates。结果解析不会改变 Date 报告其值的方式。

Date#toString 只是其内容的转储。您无法更改此设置,但您可以按照自己喜欢的方式格式化 Date 对象

try {
Date myDate = new Date();
System.out.println(myDate);

SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");

// Format the date to Strings
String mdy = mdyFormat.format(myDate);
String dmy = dmyFormat.format(myDate);

// Results...
System.out.println(mdy);
System.out.println(dmy);
// Parse the Strings back to dates
// Note, the formats don't "stick" with the Date value
System.out.println(mdyFormat.parse(mdy));
System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
exp.printStackTrace();
}

哪些输出...

Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013

另外,请注意格式模式。仔细看看SimpleDateFormat以确保您没有使用错误的模式;)

关于java.util.Date格式转换yyyy-mm-dd到mm-dd-yyyy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18480633/

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