Convert java date to json date - java

Please some one help me on this
I have a simple Date object like:
Date dt = new Date();
I want to convert it to json date format like:
"\/Date(928164000000-0400)\/"
How to do that.

Use
Date dt = new Date();
"\/Date(" + dt.getTime() + "-0400)\/"
You probably need to parse the getTime() first, depending on what your current date format is.

This is using com.google.gson.*
final JsonSerializer<Date> dateSerialize = new JsonSerializer<Date>()
{
#Override
public JsonElement serialize(final Date src,
final Type typeOfSrc,
final JsonSerializationContext context)
{
final String dateString = "Date(" + src.getTime() + "-" + src.getTimezoneOffset()+")";
return new JsonPrimitive(dateString);
}
};
Gson gson = GsonBuilder().registerTypeAdapter(Date.class, dateSerialize)
.create();
Date dt = new Date();*
gson.toJson(dt);

There isn't really a Date format in JSON, only some not universal conventions.
This being said, your "date" is in two parts :
a number of milliseconds since epoch. You can get this in UTC using the getTime() method
a time zone offset
But a java Date (contrary to a calendar), just like a javascript one, doesn't contain the time offset (getTimezoneOffset() is deprecated). So you have to decide which one you want to use. Or you might, as I would do, simply send the UTC timestamp with a zero offset :
var jsonDateUTC = "Date("+javaDate.getTime()+"-0000)";

Related

How to convert timestamp date to java.util date(yyyy-mm-dd) in java

I am getting date from Oracle is in Timestamp but I need to convert it in to this format 2020-02-17 (yyyy-mm-dd) format, but currently in postman I am receiving date as "2020-02-17T09:40:37.850+0000" in this format.
Any help on this would be really appreciated
You can easily convert a java.sql.Timestamp to a java.time.LocalDate and get a date String by formatting the LocalDate like this:
public static void main(String[] args) {
// just a timestamp stub that takes "now"
java.sql.Timestamp ts = java.sql.Timestamp.from(Instant.now());
// convert it to a modern date object
LocalDate justDate = ts.toLocalDateTime().toLocalDate();
// print it using a suitable formatter
System.out.println(justDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
The output (today) is
2020-02-17
You just need Java 8 or higher for this or import a backport library.
EDIT
If you don't need a String but a java.util.Date, do it with Instant only, like this:
public static void main(String[] args) {
// just a timestamp stub that takes "now"
Instant now = Instant.now();
Timestamp ts = Timestamp.from(now);
// create an Instant from the Timestamp
Instant timestampInstant = ts.toInstant();
// and then create a Date out from that Instant
java.util.Date creationDate = java.util.Date.from(now);
// do something with the Date here...
}
But please consider using java.time wherever possible, which might be in your domain class...
private String getZonedDateTime(String startTime){
// input -> startTime: 2020-02-17T09:40:37.850+0000
// output -> 2020-02-17
return ZonedDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
Just pass the Date String which you have and get it in what format you want.
That question is answered here
And what you want exactly, to display the date with that format or save with that format.
If you want display the date with (yyyy-mm-dd)
String dateFormated = new SimpleDateFormat("yyyy-MM-dd").format(myTimestamp);
System.out.println(dateFormated);
If you want save the date with that format you can try to do this:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd);
String dateFormated = dateFormat.format(myTimestamp);
Date parsedDate = dateFormat.parse(dateFormated);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) {
}

Milliseconds automatically added to java.util.Date / Joda DateTime

I'm trying to create a java.util.Date object without the milliseconds part. eg: 2018-03-19T15:04:23+00:00. This is the code I have:
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date d = new Date();
String strFromD = sf.format(d);
Date dFromStr = sf.parse(strFromD);
When I debug this and inspect the variables, I see this:
The String which I get by formatting the date does not have any milliseconds. However, when I create a date back from the String, it has the milliseconds part.
I tried the same using Joda DateTime as well:
DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTimeNoMillis();
DateTime dt = new DateTime();
String strFromDt = dateFormatter.print(dt);
DateTime dtFromStr = dateFormatter.parseDateTime(strFromDt);
System.out.println("DT : "+dt);
System.out.println("String from DT : "+strFromDt);
System.out.println("DT from String : "+dtFromStr);
And this is the output:
DT : 2018-03-22T09:30:22.996-07:00
String from DT : 2018-03-22T09:30:22-07:00
DT from String : 2018-03-22T09:30:22.000-07:00
Again, when I try to get the DateTime from the String, it adds the milliseconds back.
Am I missing something here? Do I need to use 2 different formatters or something?
If your SDK expects a java.util.Date, there's no point talking about a format, because dates don't have a format.
The Date class represents one numerical value: the number of milliseconds since Unix Epoch (Jan 1st 1970, at midnight, in UTC). To make a date without the milliseconds, you could truncate this milliseconds value:
Date d = new Date();
// truncate the number of milliseconds since epoch (eliminate milliseconds precision)
long secs = d.getTime() / 1000;
// create new Date with truncated value
d = new Date(secs * 1000);
In Joda-Time, it's a little bit simpler:
// set milliseconds to zero
DateTime dt = new DateTime().withMillisOfSecond(0);
// convert to java.util.Date
Date date = dt.toDate();
If your SDK expects a String, though, then it makes sense talking about formats. A date can be represented (aka "transformed in text") in many different ways:
2018-03-22T09:30:22-07:00
March 22nd 2018, 9:30:22 AM
22/03/2018 09:30:22.000
and so on...
Objects like java.util.Date and Joda's DateTime don't have a format. They just hold values (usually, numerical values), so if your SDK expects one of those objects, just pass them and don't worry about it.
If the SDK expects a String in a specific format (a text representing a date), then you should transform your date objects to that format.
And if this format doesn't allow milliseconds, so be it:
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String dateFormattedAsString = sdf.format(d);
With Joda-Time:
DateTime dt = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
String dateFormattedAsString = fmt.print(dt);
Those will not change the date's values, but the strings won't have the milliseconds printed.

Converting timestamp from parse.com in java

I'm getting my object's createdAt timestamp back from parse.com as 2014-08-01T01:17:56.751Z. I have a class that converts it to relative time.
public static String timeAgo(String time){
PrettyTime mPtime = new PrettyTime();
long timeAgo = timeStringtoMilis(time);
return mPtime.format( new Date( timeAgo ) );
}
public static long timeStringtoMilis(String time) {
long milis = 0;
try {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sd.parse(time);
milis = date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return milis;
}
The problem is that this parses the date wrongly. Right now the result says 4 decades ago and this very wrong. What I'm I doing wrong?
Your current date format "yyyy-MM-dd HH:mm:ss" does not work for the given example 2014-08-01T01:17:56.751Z. The format is missing the characters T and Z and the milliseconds.
Change it to:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
to fix it.
Also check the examples in the JavaDoc of SimpleDateFormat, because it also shows the correct date format for your example: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
Expanding #Tom's answer:
The problem
When hardcoding 'Z', you assume that all dates were saved as UTC - which doesn't necessarily have to be the case.
The problem is that SimpleDateFormat does not recognize the literal 'Z'as an alias for UTC's '-0000' offset (For whatever reason, since it claims to be ISO-8601 compliant).
So you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
since this wrongly assumes all dates will always be written as in UTC, but you can't do
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
either, since this would not be able to parse the date when the literal 'Z' occurs.
Solution 1: Use javax.xml.bind.DatatypeConverter
This datatype converter actually is ISO8601 compliant and can be used as easy as
import javax.xml.bind.DatatypeConverter;
public Long isoToMillis(String dateString){
Calendar calendar = DatatypeConverter.parseDateTime(dateString);
return calendar.getTime().getTime();
}
If you use JAXB anyway, that would be the way to go.
Solution 2: Use conditional formats
final static String ZULUFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final static String OFFSETFORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
/* This is a utility method, so you want the calling method
* to be informed that something is wrong with the input format
*/
public static Long isoToMillis(String dateString) throws ParseException{
/* It is the default, so we should use it by default */
String formatString = ZULUFORMAT;
if(! dateString.endsWith("Z") ) {
formatString = OFFSETFORMAT;
}
SimpleDateFormat sd = new SimpleDateFormat(formatString);
return sd.parse(dateString).getTime();
}
If you don't already use JAXB, you might want to put this method into a utility class.

Converting String to Date

How can I parse the following String "1394133302" which correspond of Date.toString value to a Date value (java utils).
Is it possible with a SimpleDateFormat?
Use code below
new Date(Long.valueOf("1394133302"))
PS. It seems you date string is in second, maybe you want this(convert it to millesecond!)
new Date(Long.valueOf("1394133302") * 1000L)
Just feed it back into the Date constructor:
long dateAsLong = Long.parseLong( "1394133302");
Date someDate = new Date(dateAsLong);
SimpleDateFormat is used for formatting Date value, in your case you already have a long date value in terms of Stringconvert it to Long and pass it directly to Date constructor to get date Object
Date dt = new Date(Long.valueOf("1394133302"));

String to joda LocalDate in format of "dd-MMM-yy"

I am using JAXB and joda time 2.2. to backup the data from Mysql to XML and restore it back. in my Table I have a Date attribute in format of "16-Mar-05". I successfully store this in XML. but when I want to read it from XML and put it back in Mysql table, I cant get the right format.
this is my XMLAdapter class, here in unmarshal method the input String is "16-Mar-05", but I cant get the localDate variable in the format of "16-Mar-05", although I am setting pattern to "dd-MMM-yy". I posted all the options I tried, how can I get my localDate in "dd-MMM-yy" like 16-Mar-05format?
Thanks!!
public class DateAdapter extends XmlAdapter<String, LocalDate> {
// the desired format
private String pattern = "dd-MMM-yy";
#Override
public String marshal(LocalDate date) throws Exception {
//return new SimpleDateFormat(pattern).format(date);
return date.toString("dd-MMM-yy");
}
#Override
public LocalDate unmarshal(String date) throws Exception {
if (date == null) {
return null;
} else {
//first way
final DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
final LocalDate localDate2 = dtf.parseLocalDate(date);
//second way
LocalDate localDate3 = LocalDate.parse(date,DateTimeFormat.forPattern("dd-MMM-yy"));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
return localDate4;
}
}
So I took your code and ran it and it works fine for me...
The problem, I think, you're having is that you're expecting a LocalDate object to maintain the format that you original parsed the object with, this is not how LocalDate works.
LocalDate is a representation of date or period in time, it is not a format.
LocalDate has a toString method which can be used to dump the value of the object, it, this is a internal format used by the object to provide a human readable representation.
To format the date, you need to use some kind of formater, that will take the pattern you want and a date value and return a String
For example, the following code...
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String date = "16-Mar-05";
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
LocalDate localDate2 = dtf.parseLocalDate(date);
System.out.println(localDate2 + "/" + dtf.print(localDate2));
//second way
LocalDate localDate3 = LocalDate.parse(date, DateTimeFormat.forPattern("dd-MMM-yy"));
System.out.println(localDate3 + "/" + dtf.print(localDate3));
//third way
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = FORMATTER.parseDateTime(date);
LocalDate localDate4 = dateTime.toLocalDate();
System.out.println(localDate4 + "/" + FORMATTER.print(localDate4));
Produced...
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
2005-03-16/16-Mar-05
Before you get upset about this, this is how Java Date works as well.

Categories