I am consuming an API that produces dates as Epoch timestamps but in string format:
{ "date":"1499762012700"}
Is there any way of getting this to go into a pojo as a Date object without writing some sort of custom serializer etc?
This works fine if the timestamp is a number but unfortunately this is the way it is given.
Is it a 9 digit timestamp? It would be helpful to have an actual example. If its unix time and do you want a java Date or a JODA object. I'd go with JODA
If its a unix 10 digit time stamp look here
Java: Date from unix timestamp
or
Related
So I have an object ('Task') that has an attribute 'Start Date' which is basically a Timestamp object. So this date is in this format 'YYYY/MM/dd hh:mm:ss:ms'. But for a test case I am authoring, I need this date to be in this format 'YYYY/MM/dd hh:mm'. Also it needs to be a timestamp object as I have to set this value back to the 'Task' object.
I have tried several approaches including the snippet shown below:
SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd hh:mm");
if (task.getStartDate() != null) {
String newDate = formatter.format(task.getStartDate());
Date date = formatter.parse(newDate);
task.setStartDate(new Timestamp(date.getTime()));
}
I expected the value of the timestamp to be in the format '2018-12-30 09:54' but it resulted in '2018-12-30 09:54:00.0'. So the questions that I have in mind is:
Is there a way to not consider the seconds and millis in the Timestamp object?
If no, then, is the snippet provided an efficient way to update the Timestamp object?
TL;DR
Avoid the Timestamp class if you can. It’s poorly designed and long outdated.
To answer your questions, no, a Timestamp hasn’t got, as in cannot have a format (the same holds true for its modern replacement, Instant (or LocalDateTime)).
Under all circumstances avoid SimpleDateFormat and Date. The former in particular is notoriously troublesome, and both are long outdated too.
Don’t put a format into your model class
You should not want an Instant nor a Timestamp with a specific format. Good practice in all but the simplest throw-away programs is to keep your user interface apart from your model and your business logic. The value of the Instant object belongs in your model, so keep your Instant or Timestamp there and never let the user see it directly. I hope that it’s clear to you that 2018-12-30 09:54 and 2018-12-30 09:54:00.0 represent the same value, the same Timestamp. Just like 17, 0017 and 0x11 represent the same integer value. When you adhere to what I said, it will never matter which format the Instant has got.
Whenever the user should see the date and time, this happens in the UI, not in the model. Format it into a String and show the string to the user. Similarly if you need a specific format for persistence or exchange with another system, format the Instant into a string for that purpose.
java.time and JDBC 4.2
Also for exchange with your database over JDBC, provided that you’ve got a JDBC 4.2 compliant driver, prefer to use a type from java.time over Timestamp. If the datatype on the database side is timestamp with time zone, very clearly recommended for a timestamp, pass an OffsetDateTime like
OffsetDateTime dateTime = yourInstant.atOffset(ZoneOffset.UTC);
yourPreparedStatement.setObject(4, dateTime);
Use setObject, not setTimestamp. Some drivers accept the Instant directly, without conversion to OffsetDateTime. If on the database side you need a mere timestamp (without time zone), use LocalDateTime in Java instead and pass one to setObject in the same way as above.
PS There are errors in your format pattern string
In a format pattern string, uppercase YYYY is for week based year and only useful with a week number. For year use either uuuu or lowercase yyyy. Similarly lowercase hh is for hour within AM or PM from 01 through 12 and only useful with an AM or PM marker. For hour of day from 00 through 23 you need uppercase HH. These errors will give you incorrect dates and times in most cases. Using the wrong case of format pattern letters is a very common mistake. SimpleDateFormat generally doesn’t mind, it just gives incorrect results. The modern DateTimeFormatter does a somewhat better job of notifying you of such errors.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Related questions
Formatting timestamp in Java about getting rid of the .0 decimal on the second of a Timestamp.
timestamp formatting in scala [duplicate] about getting a Timestamp with only date and hour (no minute, second or fraction of second).
java parsing string to date about uppercase Y for year in a format pattern string.
Comparing two times in android about lowercase h for hour of day in a format pattern string.
I have JSON as in the picture below which I use in my android application. I have problems with parse of sunrise and sunset which in unix, UTC format. My question is how to show only local hour and minute?
Thats what I tried to sunrise but it was wrong: sunrise.setText(json.getJSONObject("sys").getString("sunrise"));
Thanks for any help!
I believe that you have a couple of issues.
The first is how to convert a Unix timestamp into a Java Date.
Like Unix timestamps, Java dates are stored internally as a long offset from a specific instant, known as the "epoch". Fortunately, they both use the same epoch. However, Unix timestamps have higher resolution.
To get a long that represents a Java date from a Unix timestamp, you need to multiply it by 1000. Then you can use the result to initialize a Java Date.
The essential thing here is to make sure that your timestamps are longs, not ints (or doubles, or any other numeric type).
So, essentially:
long unixTimestamp = 1427607706;
long javaTimestamp = unixTimestamp * 1000L;
Date date = new Date(javaTimestamp);
Next, you'll need to get the numeric value from the Json, as a long, instead of a String, so use getLong instead of getString.
Finally, you'll want to format the date. Since you want just the hours and minutes, you can use:
String sunrise = new SimpleDateFormat("hh:mm").format(date);
and then use that value to set the value of your TextView.
I am pulling data from an external source into my program and it has an ISO8601 Date attached to it but one of our requirements is that the hour/minutes/seconds get set to zero. This happens before I receive the date. So I get this from the data.
2013-05-17T00:00:00.000Z
for instance. I am then putting that value into a Joda DateTime object called "businessDay". I do some processing based off of this value but then I need to persist it to MongoDB.
Since a Joda DateTime object is not serializable I need to put the DateTime object into a Date object and persist it to Mongo (and reverse that when it comes out).
When I use Joda in this way
businessDay.toDate() -- I receive a Java Date object but it is
Sun May 19 20:00:00 EDT 2013
and businessDay printed out normally is
2013-05-20T00:00:00.000Z
It converts it to my local time zone, which is then making it the previous day.
What I want is to convert the DateTime object into a Date object that retains the values.
I've been trying a bunch of things with DateTimeFormatter but I can't get it to work at all. I've also been deleting all of my efforts otherwise I would paste them here but I've been doing this all day to try to figure this out.
Thank you for any assistance.
EDIT:
Showing method that converts a String Date into a Joda DateTime object.
private DateTime asDateTime(String value) {
// Was experiencing an issue converting DateTime to date, it would convert to localtime zone
// giving me the wrong date. I am splitting the value into its year/month/day values and using a dateFormatter
// to give me an appropriate format for the date. Timezone is based on UTC.
String[] splitValue = value.split("-");
String[] splitDay = splitValue[2].split("T");
int year = Integer.parseInt(splitValue[0]);
int month = Integer.parseInt(splitValue[1]);
int day = Integer.parseInt(splitDay[0]);
DateTime date = new DateTime(DateTimeZone.UTC).withDate(year, month, day).withTime(0, 0, 0, 0);
return date;
}
Firstly, if you've just got a date, I would suggest using LocalDate rather than DateTime. However, I think you've misunderstood what java.util.Date does:
It converts it to my local time zone, which is then making it the previous day.
No, it really doesn't. Your DateTime value is precisely 2013-05-20T00:00:00.000Z. Now a java.util.Date is just a number of milliseconds since the Unix epoch. It doesn't have the concept of a time zone at all. It's equivalent to a Joda Time Instant.
When you call toString() on a Date, that converts the instant in time into your local time zone - but that's not part of the state of the object.
So both your DateTime and your Date represent midnight on May 20th UTC. I don't know what MongoDB is then doing with the value, but just the conversion from Joda Time to java.util.Date has not performed any time zone conversion for you.
My apologies, I found out that it wasn't an issue of the Dates it was a completely different issue. MongoDB can accept a Java Date and will convert it to UTC format automatically.
My fault for creating this post before looking at this problem from different angles.
Do I accept the other answer and give the bounty? Just curious if that is the correct thing to do on Stack Overflow.
I have a PHP web service sending JSON responses back to my Java client. One of the fields is a DateTime value. However, I'm having problems translating the serialized PHP Date/Time to a Java Date.
For example, here is a date stored in my database:
2011-12-07 15:03:01
Here is how it's encoded in the JSON response:
1323288181
I suspected this would be the milliseconds since the Unix epoch, but when I construct a Java Date with that given value, the date turns out to be the following:
Fri Jan 16 01:34:48 CST 1970
Obviously it's not milliseconds since January 1, 1970 at midnight.
How do I go about doing this?
Looks like that's seconds since the Unix epoch - so just multiply your value by 1000 when passing it to the Date constructor.
Note that Date.toString() will always use the system time zone, but a Date really represents an instant in time, so it doesn't have a time zone.
If you're doing anything significant with dates and times, I'd thoroughly recommend using Joda Time instead of the classes in java.util.
I think it is a unixtimestamp. use this online convertor: http://www.onlineconversion.com/unix_time.htm
and here are examples how to convert it (in java):
http://www.epochconverter.com/
I am using
1970-01-01T00:00:00Z
as date time format in JSON,
then I make sure both sides parse it correctly
How can I convert time in unix timestamp to normal time?
Your question is vague and ambiguous. I'll leave the timezone ambiguity away.
How can I convert time in unix timestamp to normal time?
I suspect that you're somehow obtaining a long or maybe a String value from the DB instead of a Date. In JDBC, you would normally like to use the appropriate methods to obtain the DB-specific datatypes. The MySQL TIMESTAMP datatype can be obtained by ResultSet#getTimestamp() which gives you a java.sql.Timestamp which in turn is a subclass of java.util.Date.
In a nut, the following should do:
Date date = resultSet.getTimestamp("columnname");
To format it further in a human readable format whenever you're going to present it to the enduser, use SimpleDateFormat. Click the link, it contains an overview of all patterns. Here's an example:
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
To do all the other way round, use respectively SimpleDateFormat#parse() and PreparedStatement#setTimestamp().
Unix timestamp is seconds since "epoch". Java's currentTimeMillis are milliseconds since "epoch". You can get a Java Date object with a simple multiplication like this:
Date dateFromUnixTime = new Date( 1000l * unixTime) ;
From there, you can format it using the normal date formatting tools in Java.