Java SimpleDateFormat类似于C# [英] Java SimpleDateFormat similar to C#

查看:148
本文介绍了Java SimpleDateFormat类似于C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用这种格式获得今天的日期 {Date:2013-09-11T14:47:57.8895887 + 02:00}
这是因为我的Json服务被研究Windows Phone和C#代码。

I have to get a today Date with this format {"Date":"2013-09-11T14:47:57.8895887+02:00"}. This is because my Json Service is studied for Windows Phone and C# code.

我尝试使用这种方法:

public static Date getTodayDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSSZ:Z");
    Date date = new Date();
    String dateString = dateFormat.format(date);
    Date today = parseFromNormalStringToDate(dateString);
    return today;
}

但我得到这个退货


2013-09-16T11:47:55.235 + 0200:+0200;

2013-09-16T11:47:55.235+0200:+0200;

谢谢为了帮助!

推荐答案

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

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

这篇关于Java SimpleDateFormat类似于C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆