且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java SimpleDateFormat类似于C#

更新时间:2022-06-27 01:05:35

这里有两件事要改变。首先是格式。

There are 2 things to be changed here. First the format.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX"); // This should work for you. Though I must say 6 "S" is not done. You won't get milliseconds for 6 precisions.
Date date = new Date();
String dateString = dateFormat.format(date); // You need to use "dateString" for your JSON

使用dateString。第二件事,格式化日期是您需要将其放入JSON中,而不是将其解析回 Date 。但是 Date 没有格式化选项。您只能使用SDF格式获取日期的String表示形式。

And the second thing, the formatted date is the which you need to put in your JSON and not parse it back to Date. But Date doesn't have a formatting option. You can only get a String representation of the Date in the format you need using SDF.

例如:

public static void main(String[] args) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX");
    Date date = new Date();
    String dateString = dateFormat.format(date); // You need to use "dateString" for your JSON
    System.out.println(dateString); // Output
}

这个输出是


2013-09-16T15:39:16.000257 + 05:30

2013-09-16T15:39:16.000257+05:30

毫秒级的6位精度是不可能的。如果您在Java 7中看到SDF的文档,可以找到: -

6 digit precision in milliseconds is not possible. If you see the docs of SDF in Java 7, you can find this:-

突出显示的示例是您需要的示例,但精度为6毫秒,这是不可能的。因此,您可以使用6 S ,但它只会在实际的3毫秒数字之前添加3个前导零!这是您情况下唯一的解决办法!

The highlighted example is the one you need, but with 6 milliseconds precision, which is not possible. Thus, you can use 6 S but it will just add 3 leading zeroes before the actual 3 millisecond digits! This is the only workaround possible in your case!

编辑: -

SimpleDateFormat 的Android不包含 X 。它提供 Z 。因此,您的新格式字符串将

The SimpleDateFormat of Android does not contain X. It provides Z instead. Therefore your new format string will be


yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ

yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ



SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"); // For Android