Convert JSON Date Format

I get a JSON object with a date value as follows:

{"PostingDate":"\/Date(1325134800000-0500)\/"} 

And I want to parse it in Java code before Date or get it as String .

I want to know that this is an easy way to do this.

+6
source share
5 answers

I accept this first number ( 1325134800000 ) - this is the number of milliseconds since the era, and -0500 is the time zone. This is similar to the case with the code example below, which seems to do what you want.

The following code parses JSON input using Jackson , which I recommend if you do not already have a library for parsing JSON, It does not have error checking, etc.

Code example:

 public final class Foo { public static void main(final String... args) throws IOException { // What the JSON value must match exactly // Not anchored since it will be used with the (misnamed) .matches() method final Pattern pattern = Pattern.compile("\\\\/Date\\((\\d+)(-\\d+)?\\)\\\\/"); final ObjectMapper mapper = new ObjectMapper(); // Parse JSON... final JsonNode node = mapper.readTree( "{\"PostingDate\": \"\\/Date(1325134800000-0500)\\/\"}"); if (!node.has("PostingDate")) { System.err.println("Bad JSON input!"); System.exit(1); } // Get relevant field final String dateSpec = node.get("PostingDate").getTextValue(); // Try and match the input. final Matcher matcher = pattern.matcher(dateSpec); if (!matcher.matches()) { System.err.println("Bad pattern!"); // Yuck System.exit(1); } // The first group capture the milliseconds, the second one the time zone final long millis = Long.parseLong(matcher.group(1)); String tz = matcher.group(2); if (tz.isEmpty()) // It can happen, in which case the default is assumed to be... tz = "+0000"; // Instantiate a date object... final Date date = new Date(millis); // And print it using an appropriate date format System.out.printf("Date: %s %s\n", new SimpleDateFormat("yyyy/MM/dd HH:MM:ss").format(date), tz); } } 

Conclusion:

 Date: 2011/12/29 06:12:00 -0500 
+5
source

Hier is a working parsing method based on the fge version but improved as

  • he used jode DateTime with the correct timezone initialized
  • minor change of template for adoption +0200 too

=>

 private static final Pattern bingTimePattern = Pattern.compile("\\/Date\\((\\d+)([-+]\\d+)?\\)\\/"); public static DateTime parseBingTime(String timeAsString) throws ParseException { Matcher matcher = bingTimePattern.matcher(timeAsString); if (!matcher.find()) throw new ParseException("wrong date time format " + timeAsString, 0); final long millis = Long.parseLong(matcher.group(1)); String tz = matcher.group(2); if (tz.isEmpty()) tz = "+0000"; return new DateTime(millis, DateTimeZone.forID(tz)); } 
0
source

I created a simple JavaScript function using jQuery DatePicker

  function JsonToJSDate(jsonDate) { var reg = /-?\d+/; var m = reg.exec(jsonDate); return new Date(parseInt(m[0])); } 

$ ('# Started'). val ($. datepicker.formatDate ('mm / dd / yy', JsonToJSDate (yourDateVarHere)));

0
source

A simple thing, but the processing of my work. Extract the value of your object from JSON and apply a substring.
eg:

  String postingDateObjectValue = "\\/Date(1442436473422)\\/"; String dateStringInMillis = postingDateObjectValue .substring(7,20); 

now analyze milliseeds and use them wherever you want.

0
source

In Java> = 8, you can use the new java.time API .

Input contains:

  • a unix timestamp ( 1325134800000 ), which is the number of milliseconds since unix ( 1970-01-01T00:00Z )
  • a UTC offset ( -0500 ), which is a difference from UTC (in this case, 5 hours after UTC)

There are many different types of date / time objects in the new java.time API. In this case, we can choose a java.time.Instant (which represents the number of nanoseconds since unix) or java.time.OffsetDateTime (which represents Instant , converted to a date / time at a specific offset).

To java.time.format.DateTimeFormatterBuilder String , I use java.time.format.DateTimeFormatterBuilder to create java.time.format.DateTimeFormatter . I also use java.time.temporal.ChronoField to indicate which fields are processed:

 DateTimeFormatter fmt = new DateTimeFormatterBuilder() // epoch seconds .appendValue(ChronoField.INSTANT_SECONDS) // milliseconds .appendValue(ChronoField.MILLI_OF_SECOND, 3) // offset .appendPattern("xx") // create formatter .toFormatter(); 

I also use regex to extract only the relevant part from String input (although you can also use substring() to get it):

 String s = "/Date(1325134800000-0500)/"; // get just the "1325134800000-0500" part - you can also do s.substring(6, 24) s = s.replaceAll(".*/Date\\(([\\d\\+\\-]+)\\)/.*", "$1"); 

Then I can parse the type I want:

 // parse to Instant Instant instant = Instant.from(fmt.parse(s)); // parse to OffsetDateTime OffsetDateTime odt = OffsetDateTime.parse(s, fmt); 

Instant equivalent to 2011-12-29T05:00:00Z ( Instant is just a point on the timeline, and you may think that it is always in UTC). OffsetDateTime has the same moment, but is converted to an offset of -0500 , so its value is 2011-12-29T00:00-05:00 . But both Instant and OffsetDateTime represent the same point in time.


To convert to java.util.Date , use Instant :

 // convert to java.util.Date Date date = Date.from(instant); // if you have an OffsetDateTime, you can do this: Date date = Date.from(odt.toInstant()); 

This is because java.util.Date does not have timezone / offset information , and it simply represents the number of milliseconds since unix (same concept of Instant ), so it can be easily converted from Instant .


Java 6 and 7

For Java 6 and 7, you can use ThreeTen Backport , the excellent backport for Java 8 of the new date and time classes. And for Android, you'll also need ThreeTenABP (more on how to use it here ).

The difference from Java 8 is package names (in Java 8 it is java.time , and in ThreeTen Backport (or Android ThreeTenABP) it is org.threeten.bp ), but the classes and methods of names are the same. Thus, the formatting and parsing code for Instant and OffsetDateTime same.

Another difference is that in Java <= 7, the java.util.Date class does not have a from() method. But you can use the org.threeten.bp.DateTimeUtils class to convert:

 // convert to java.util.Date Date date = DateTimeUtils.toDate(instant); // or from the OffsetDateTime Date date = DateTimeUtils.toDate(odt.toInstant()); 
0
source

Source: https://habr.com/ru/post/904889/


All Articles