Convert JSON Date to Java Date

JSON date to Java date?

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

Here's one

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

Convert Json date to java date

JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Timestamp stamp = new Timestamp(store.getLong("CreatedOn"));
Date date = new Date(stamp.getTime());
System.out.println(date);
}

or

JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
Date date = new Date(datetimestamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
String dateFormatted = formatter.format(date);
}

consider using JSON methods instead of contains. JSON has "has()" which validate if key exists.

You should also make sure that you try {} catch {} the String first, to make sure its valid JSON.

Update:

Your Value is
/Date(1406192939581)/

which means it must be formatted first.
Get it by parsing the string with

Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));

Convert java.util.Date to json format

RestEasy supports JSON via Jackson, so you can handle Date serialization in several ways.

1. @JsonFormat annotation

If you want to format specific field - simply add @JsonFormat annotation to your POJO.

public class TestPojo {

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
public Date testDate;
}

2. Jackson properties

If you want to set Date serialization format globally - you have to tune Jackson configuration properties. E.g. for application.properties file format.

First one disables WRITE_DATES_AS_TIMESTAMPS serialization feature:

spring.jackson.serialization.write-dates-as-timestamps=false

Second one defines date format:

spring.jackson.date-format=dd-MM-yyyy

Or, for application.yml file format:

spring:
jackson:
date-format: "dd-MM-yyyy"
serialization:
write_dates_as_timestamps: false

3. Custom Serializer

If you want to take full control over serialization - you have to implement a custom StdSerializer.

public class CustomDateSerializer extends StdSerializer<Date> {

private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

public CustomDateSerializer() {
this(null);
}

public CustomDateSerializer(Class t) {
super(t);
}

@Override
public void serialize(Date date, JsonGenerator generator, SerializerProvider provider)
throws IOException, JsonProcessingException {

generator.writeString(formatter.format(date));
}
}

And then use it with @JsonSerialize:

public class TestPojo {

@JsonSerialize(using = CustomDateSerializer.class)
public Date testDate;
}

Json Date \/Date(1389715867000)/ to convert to java.util.Date in java

String policyEffective = ...

long time = Long.parseLong(policyEffective.replaceFirst("^.*Date\\((\\d+)\\).*$", "$1"));
Date date = new Date(time);

The number is a long, ms since 1970 or so, and goes as such into the Date constructor.

Result:

Tue Jan 14 17:11:07 CET 2014

Since you got an illegal argument; maybe you took an int or something else.

convert Json Date with Offset to java date

Here's an example on how to parse your custom dates.

// test value
String[] jsonDates = {"/Date(1463667774000-9000)/","/Date(1463667774000)/", "/Date(1463667774000+0400)/"};
// | preceded by "("
// | | group 1: timestamp
// | | | optional group 2: "+" or "-"
// | | | | optional group 3
// | | | | (within group 2):
// | | | | minutes
// | | | | | followed by ")"
Pattern p = Pattern.compile("(?<=\\()(\\d+)(([-+])(\\d+))?(?=\\))");
for (String jsonDate: jsonDates) {
Matcher m = p.matcher(jsonDate);
// matching pattern...
if (m.find()) {
// found: parsing timstamp
long timestamp = Long.parseLong(m.group(1));
Integer minutes = null;
Boolean addOrSubstract = null;
if (m.group(2) != null) {
// parsing sign
addOrSubstract = "+".equals(m.group(3));
// parsing minutes
if (m.group(4) != null) {
minutes = Integer.parseInt(m.group(4));
}
}

// initializing calendar
Calendar c = Calendar.getInstance();
c.setTime(new Date(timestamp));
// adding/removing minutes if parsed
if (minutes != null) {
c.add(
Calendar.MINUTE,
addOrSubstract != null ?
(addOrSubstract ? minutes : -minutes) : 0
);
}
Date date = c.getTime();
System.out.println(date);
}
// not matched, different format
else {
// TODO error
}
}

Convert JSON date format

I take it the first number (1325134800000) is the number of milliseconds since epoch, and -0500 is the time zone. This appears to be the case given the sample code below, which seems to do what you want.

The following code parses the JSON input using Jackson, which I recommend if you don't have a JSON parsing library of choice yet. It lacks error checking etc.

Sample code:

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);
}
}

Output:

Date: 2011/12/29 06:12:00 -0500

how to convert the json string date to Date format in android

Try this.

SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");
Date myDate = myFormat.parse("your date string here");


Related Topics



Leave a reply



Submit