datetime json
Par PlaceOweb le samedi, janvier 9 2021, 21:30 - Outils Internet - Lien permanent
Comment est converti un Datetime en JSON avec le serializer par défaut ? convertisseur sérialisation JSON (marshaling)
Vers 21h30 heure locale de Paris (et actuellement +1h avec le GMT "Greenwich Mean Time") :
C# csharp
DateTime dt = new DateTime();
DateTime dt = DateTime.Now;
Console.WriteLine(dt);
Console.WriteLine(JsonConvert.SerializeObject(dt));
DateTimeOffset dto = new DateTimeOffset();
DateTimeOffset dto = DateTimeOffset.Now;
Console.WriteLine(dto);
Console.WriteLine(JsonConvert.SerializeObject(dto));
01/01/0001 00:00:00
"0001-01-01T00:00:00"
09/01/2021 21:30:04
"2021-01-09T21:30:04.8990838+01:00"
01/01/0001 00:00:00 +00:00
"0001-01-01T00:00:00+00:00"
09/01/2021 21:30:32 +01:00
"2021-01-09T21:30:32.0263658+01:00"
Java - com.google.code.gson » gson, org.json » json, net.sf.json-lib » json-lib, com.fasterxml.jackson.core » jackson-core
Date dt = new Date();
System.out.println(dt); //Sat Jan 09 21:25:20 CET 2021
String json = new Gson().toJson(dt);
System.out.println(json); //"Jan 9, 2021, 9:25:20 PM"
JSONObject jsonObject = JSONObject.fromObject(dt);
System.out.println(jsonObject); //java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException | net/sf/ezmorph/Morpher | org/apache/commons/logging/LogFactory | rg/apache/commons/logging/LogFactory | org/apache/commons/collections/map/ListOrderedMap | org/apache/commons/beanutils/DynaBean
// {"date":9,"hours":21,"seconds":20,"month":0,"timezoneOffset":-60,"year":121,"minutes":25,"time":1610223920730,"day":6}
// Creating Object of ObjectMapper define in Jakson Api
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(dt)); // 1610223920730
// https://www.baeldung.com/jackson-serialize-dates
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
System.out.println(objectMapper.writeValueAsString(dt)); // "2021-01-09T20:25:20.730+00:00"
Javascript
var dt = new Date();
console.log(dt);
console.log(JSON.stringify(dt));
Date Sat Jan 09 2021 21:32:48 GMT+0100 (heure normale d’Europe centrale)
"2021-01-09T20:32:48.912Z"
Node.js
> var dt = new Date();
undefined
> dt
2021-01-09T20:28:34.253Z
> console.log(dt.toJSON())
2021-01-09T20:28:34.253Z
PHP
// avec php.ini
// [Date]
// date.timezone = Europe/Paris
$dt = new DateTime();
echo json_encode($dt);
{"date":"2021-01-09 21:32:05.109686","timezone_type":3,"timezone":"Europe\/Paris"}