简体   繁体   English

将日期格式转换为不同日期格式,如edm

[英]convert date format to diffrent date format like edm

Im having field type java.util.date and from it im getting the value of to.string() Sat Sep 14 00:00:00 IDT 2013 but I need to get it in different format which is EDM format like 2013-09-12T14:00 . 我具有字段类型java.util.date,并从中获取to.string()的值。IDT 2013年9月14日星期六00:00:00,但我需要以其他格式获取它,例如2013-09-年的EDM格式12T14:00。 There is simple way to do that? 有简单的方法可以做到吗?

Thanks! 谢谢!

Use SimpleDateFormat (a good tutorial is available here ). 使用SimpleDateFormat (可在此处找到一个很好的教程)。 Consider this example: 考虑以下示例:

Date date = new Date();
System.out.println(date);

which outputs: 输出:

Mon Jun 24 21:46:22 BST 2013 2013年6月24日星期一21:46:22 BST

To convert to EDM format, do the following: 要转换为EDM格式,请执行以下操作:

String firstPartOfPattern = "yyyy-MM-dd";
String secondPartOfPattern = "HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(firstPartOfPattern);
SimpleDateFormat sdf2 = new SimpleDateFormat(secondPartOfPattern);
String formattedDate = sdf1.format(date) + "T" + sdf2.format(date);

formattedDate now has the following format: formattedDate现在具有以下格式:

2013-06-24T21:46:22 2013-06-24T21:46:22

Edit: As mentioned you shouldn't use SimpleDateFormat anymore in Java 8+! 编辑:如上所述,您不应再在Java 8+中使用SimpleDateFormat

You can do also simplify the steps described by Sam: 您还可以简化Sam所描述的步骤:

String pattern = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String formattedDate = sdf.format(date);

tl;dr TL;博士

myUtilDate.toInstant().toString()

2017-01-23T01:23:45.123Z 2017-01-23T01:23:45.123Z

ISO 8601 ISO 8601

Your desired format is defined in the ISO 8601 standard. 您所需的格式已在ISO 8601标准中定义。

The java.time classes use ISO 8601 formats by default when parsing or generating strings. 解析或生成字符串时,java.time类默认使用ISO 8601格式。

java.time java.time

Avoid using the outdated troublesome old date-time classes such as Date that are now legacy, supplanted by the java.time classes. 避免使用java.time类取代的过时且麻烦的旧日期时间类,例如Date ,现在已成为旧版。

Convert your Date object to java.time by using new methods added to the old classes. 通过使用添加到旧类中的新方法将Date对象转换为java.time。 The modern counterpart to Date is Instant for a moment on the timeline in UTC but with a finer resolution of nanoseconds rather than milliseconds. Date的现代对应物在UTC的时间轴上是“ Instant ”的,但具有更精细的纳秒而不是毫秒的分辨率。

Instant instant = myUtilDate.toInstant() ;

To generate your ISO 8601 string, simply call toString . 要生成您的ISO 8601字符串,只需调用toString The Z on the end is short for Zulu and means UTC. 末尾的Z表示Zulu ,表示UTC。

String output = instant.toString() ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM