作为 .net 服务的响应,我得到了这个日期格式: /日期(1233323754523+0100)/
1233323754523 是时间戳格式的日期,但我不知道 +0100 是什么意思以及如何从 java 代码生成它?
谢谢
最佳答案
我假设时间戳是 UTC,偏移量是所需本地时间的 UTC 偏移量。如果时间戳在给定的 UTC 偏移量内,您必须以稍微不同的方式生成它。
在 Java 中生成它的可靠方法是使用 Joda-Time库,它比默认的 java.util.Date
和 java.util.Calendar
类要好得多。
// A formatter that prints the timezone offset
DateTimeFormatter fmt = DateTimeFormat.forPattern("Z");
// The current date+time in the system default timezone.
DateTime dt = new DateTime();
// Create the result.
String result = "/Date(" + dt.getMillis() + fmt.print(dt) + ")/";
有点不幸的是 DateTimeFormat
没有办法输出自纪元以来的毫秒数;这就是需要 dt.getMillis()
字符串连接的原因。
使用 java.util
类生成相同的东西看起来像这样:
// A formatter that prints the timezone offset
SimpleDateFormat df = new SimpleDateFormat("Z");
// Current date+time in system default timezone.
Calendar now = Calendar.getInstance();
// Don't forget this if you use a timezone other than system default:
df.setTimeZone( now.getTimeZone() );
// Create the result
String result = "/Date(" now.getTimeInMillis() + df.format(now.getTime()) +")/";
它本质上与 Joda-Time 示例相同,但是您必须将时区从日历复制到日期格式化程序的地方是错误的主要来源。
关于java - .net JSON 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7589816/