如何在 Json 中发送 java.util.Date?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31784251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:37:36  来源:igfitidea点击:

How to send java.util.Date in Json?

javajsonstringhttpdate

提问by Greyshack

I need to send data in json. What's important is that I want the locale to be preserved so that the receiver gets the date in his local time. How can I do that?

我需要在json 中发送数据。重要的是我希望保留语言环境,以便接收者获得当地时间的日期。我怎样才能做到这一点?

I cannot simply use Date.toString()because then I won't be able to parse it back to date on the receiving end if their locale is different(different day and month names and so on).

我不能简单地使用,Date.toString()因为如果他们的语言环境不同(不同的日期和月份名称等),我将无法在接收端将其解析回最新的日期。

Is there a solution to this?

这个问题有方法解决吗?

采纳答案by Laurentiu L.

Use java.util.Date's getTime method for the timestamp. Once you convert it back to a date every receiver can display it using it's local time zone.

使用 java.util.Date 的 getTime 方法获取时间戳。将其转换回日期后,每个接收器都可以使用本地时区显示它。

Remember that Date

记住那个日期

represents a specific instant in time, with millisecond precision.

代表一个特定的时刻,精度为毫秒。

The toString method just formats it in a specific way:

toString 方法只是以特定方式对其进行格式化:

dow mon dd hh:mm:ss zzz yyyy

Chosing to send the timestamp means you also use less bandwidth.

选择发送时间戳意味着您也使用更少的带宽。

回答by Joop Eggen

A ms long time since 1970 is fine, but not human readable, and hence a PITA for testing/developing.

自 1970 年以来的 ms 很长一段时间很好,但不是人类可读的,因此是用于测试/开发的 PITA。

Hence use the ISO 8601standard date time"yyyy-MM-dd'T'HH:mm:ss"(where 'T'is just a literal T(one often sees a space here; and fractional seconds .SSS).

因此使用ISO 8601标准日期时间"yyyy-MM-dd'T'HH:mm:ss"(其中'T'只是一个文字T(人们经常在这里看到一个空格;和小数秒.SSS)。

Time zoneis possible too, but hopefully not needed (= incorporated in the localized time).

也是可能的,但希望不需要(= 纳入本地化时间)。

Before java 8 using SimpleDateFormat.

在 Java 8 之前使用SimpleDateFormat.

回答by mprivat

The proper way to do this is to write your date in ISO 8601 format: i.e. 2015-08-03T4:50:49+00:00

正确的方法是用 ISO 8601 格式写你的日期:即 2015-08-03T4:50:49+00:00

Not only will in include the timezone but also any standard decoder on the receiving end of your JSON will be able to decode it without problems.

不仅会包含时区,而且 JSON 接收端的任何标准解码器都可以毫无问题地对其进行解码。

For the sending part, if you are writing the string yourself, well just format it:

对于发送部分,如果您自己编写字符串,那么只需对其进行格式化:

ZonedDateTime.now( ZoneId.systemDefault() )
             .format( DateTimeFormatter.ISO_DATE_TIME )

But if you are using any JSON serializers to transform from your Java objects (like Hymanson for example), then just make the object attribute a java.util.Dateand the serializer should know what to do, given the right setup. See this answerfor Hymanson, or this onefor Jersey. They both use Joda Time.

但是,如果您使用任何 JSON 序列化程序从您的 Java 对象(例如 Hymanson)进行转换,那么只需将对象属性设置为 ajava.util.Date并且序列化程序应该知道要做什么,前提是设置正确。见这个答案Hyman逊,或者这一次的球衣。他们都使用 Joda 时间。

回答by SwapnilKumbhar

I think there is the simple way to do this,

我认为有一种简单的方法可以做到这一点,

DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
yourJsonObject.accumulate("yourDateVarible",dateFormat.format(new Date()));

回答by Basil Bourque

tl;dr

tl;博士

Instant.now()
       .toString()

2017-01-23T12:34:56.123456789Z

2017-01-23T12:34:56.123456789Z

UTC

世界标准时间

Generally best to exchange data for date-time values in UTC (GMT). Let the receiver adjust into a desired time zone.

通常最好将数据交换为 UTC (GMT) 中的日期时间值。让接收器调整到所需的时区。

Instant

Instant

The Instantclass represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant类表示UTC时间线与纳秒的分辨率上一会儿。

Instant instant = Instant.now() ;
String output = instant.toString() ;  // Generate a String in standard ISO 8601 format.

2017-01-23T12:34:56.123456789Z

2017-01-23T12:34:56.123456789Z

You can easily parse that string.

您可以轻松解析该字符串。

Instant instant = Instant.parse( "2017-01-23T12:34:56.123456789Z" ) ; 

ISO 8601

ISO 8601

The ISO 8601standard defines clear easy-to-read easy-to-parse formats for textual representations of date-time values. These formats are ideal for data-exchange.

ISO 8601标准定义清晰易于阅读易于解析格式的日期时间值的文本表示。这些格式非常适合数据交换。

For a moment in UTC, that means the format seen in example above. The Tseparates the date portion from the time of day portion. The Zon the end is short for Zuluand means UTC.

在 UTC 中,这意味着在上面的示例中看到的格式。将T日期部分与一天中的时间部分分开。在Z上月底是短期的Zulu,并指UTC。

Locale

语言环境

The Question mentions locale as if related to time zone. A Localehas nothingto do with time zone. A Localespecifies (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.

问题提到语言环境就好像与时区有关。一Locale什么做的时区。ALocale规定 (a) 翻译日名、月名等的人类语言,以及 (b) 决定缩写、大写、标点等问题的文化规范。

A time zone is a history of changes to a region's offset-from-UTC, tracking anomalies causing those changes such as Daylight Saving Time (DST).

时区是一个地区的UTC 偏移量变化的历史,跟踪导致这些变化的异常,例如夏令时 (DST)

Search Stack Overflow to learn more. This has already been covered many hundreds of times already. Search for classes such as ZoneId, ZoneOffset, ZonedDateTime, Instant, OffsetDateTime, and DateTimeFormatter. Read the Oracle Tutorialon the java.time classes.

搜索 Stack Overflow 以了解更多信息。这已经被覆盖了数百次。搜索类,如ZoneIdZoneOffsetZonedDateTimeInstantOffsetDateTime,和DateTimeFormatter。阅读有关 java.time 类的Oracle 教程

ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;


About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by fjgarzon

Try this format : 2017-03-20T00:00:00.000+0100

试试这个格式:2017-03-20T00:00:00.000+0100

回答by abhishek ringsia

There are many ways to do that. One way to convert date in milliseconds which does not depend on locale and use it further. Another way to change date in utc format and use it further.If your server's time zone set to UTC java.util.Date will work perfectly because it takes systems time zone by default while using new Date("some date").Example :

有很多方法可以做到这一点。一种以毫秒为单位转换日期的方法,它不依赖于语言环境并进一步使用它。另一种以 utc 格式更改日期并进一步使用它的方法。如果您的服务器的时区设置为 UTC java.util.Date 将完美运行,因为它在使用 new Date("some date") 时默认采用系统时区。例如:

   long lastAccessedDate =  110002028250;
  String myDate = new java.util.Date(lastAccessedDate()).toString();

myDate will be "Tue Jun 06 05:30:00 UTC 2017", if system time zone is UTC.

如果系统时区为 UTC,myDate 将是“Tue Jun 06 05:30:00 UTC 2017”。