Java 8 : How to convert timestamp to long - java-8

I am writing a back-end service and receive timestamp as shown below
Instant timestamp = Instant.now().plusMillis(offset);
bodyObject.put("timestamp", DateTimeFormatter.ISO_INSTANT.format(timestamp));
Now at my service end I want to convert this timestamp into "Long" data type for my further processing. Please guide me how can I achieve this?

I am converting the timestamp format to Instant and then using getEpochSecond() method to get seconds
Instant instant = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(format));
instant.getEpochSecond();

Related

Date conversation with time zone information

I have one issue. Solutions might be there already in this forum but I couldn't find anything. Please share if it's already answered.
The scenario is as below.
Request is coming in CET to my application which is running in UTac time zone. My backend stored procedure is running in CET zone. The time that is passed in as string with cet offset I need to send same as SQL date with same date to my backend.
Current implementation is:
Convert string date to offsetdate. Then create Instant from that offsetdate and then util date using that instant. Once I have until date I am converting that to SQL Date.
So here issue is if input request us 2012-07-15T00:00:00+02:00 then when applications which is running in UTC is giving correct offset date with cet offset information but when it is converting to instant then always UTC will come. So new date is 2012-07-14T00:00:00Z and because if this my util and SQL date is also coming 1 day behind.
Can anyone please guide if there is any other way where I can create SQL or util. Date for same date irrespective of any time zone?
Because the expectation is request can come with any time zone and we need to understand that zone and then convert or use accordingly and same date should go to back end.
API developed with: Spring boot with JAVA 8 and backend we are accessing using stored procedure where stored procedure is expecting in SQL date.
Since you can use OffsetDate and other classes from java.time, the modern Java date and time API, you should no longer be using java.util.Date nor java.sql.Date. Those classes are poorly designed and long outdated, and the modern API offers all the functionality you need. You might have thought that you needed a java.sql.Date for storing into your SQL database. But with JDBC 4.2 (or a newer JPA implementation such as Hibernate) you can directly store a LocalDate there, which you will prefer.
String requestString = "2012-07-15T00:00:00+02:00";
OffsetDateTime dateTime = OffsetDateTime.parse(requestString);
LocalDate date = dateTime.toLocalDate();
System.out.println("Date is " + date);
This prints:
Date is 2012-07-15
No day has gone lost. To save do for example:
PreparedStatement ps = yourDatabaseConnection.prepareStatement(
"insert into your_table (your_date) values (?);");
ps.setObject(1, date);
ps.executeUpdate();
Sometimes we need to pass an old-fashioned type to a legacy API that we cannot afford to change right away. If this was your reason for wanting a java.sql.Date, convert like this:
java.sql.Date sqlDate = java.sql.Date.valueOf(date);
System.out.println("Old-fashioned java.sql.Date is " + sqlDate);
Old-fashioned java.sql.Date is 2012-07-15
Still no day is lost.
Edit: If what your legacy API requires is a java.util.Date, you will need to know the way to convert:
Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
Date oldFashionedUtilDate = Date.from(startOfDay);
System.out.println("As old-fashioned java.util.Date: " + oldFashionedUtilDate);
When I run with a default time zone UTC the output is:
As old-fashioned java.util.Date: Sun Jul 15 00:00:00 UTC 2012

Timestamp to long is not correct in Apache Nifi

I want to convert string timestamp to long. I receive string timestamp like this;
2019-03-29T19:26:36.272794Z -> it has 6 number after seconds(272794)
For this, I'm using this format in UpdateRecordProcessor;
${field.value:toDate("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", "GMT"):toNumber()}
But this solution does not give the correct solution. For example, result of above timestamp string is; 1553887868794. But this is equal to: 2019-03-29T19:31:08.794Z.
I guess, UpdateRecord uses SimpleDataFormat in the backend. But, as far as I know, SimpleDateFormat is only work with 3 number after seconds like above result.
How can I get correct result in UpdateRecord of Nifi?

Date timezone getting changed when using spring boot default jackson mapping

I have spring boot rest service which call another service xyz and receive date in format yyyy-MM-ddXXX from json. But time Zone of of date is getting changed in my service response. Suppose I am getting date in JSON from service xyz as "date": "2018-08-27-07:00" but my service response is returning date : "2018-08-27-04:00". Offset getting changed. Date field in my POJO is . I want to use the same offset I am getting from backend service and it can be any offset.
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-ddXXX")
private Calendar date;
The problem is that Calendar (and Date) use implicit time conversions to adjust it to your time zone. And almost always it is something that not expected.
To avoid this use java.time classes (such as OffsetDateTime or ZonedDateTime, or even LocalDateTime if you do not need to work wit time zones).
And small offtopic advice: try to use time format aligned to ISO8601 standard (like 2018-08-24T22:30:00)

Jodas LocalDateTime with Spring Data and Couchbase has no timezone

I wanna persistant an object with LocalDateTime fields with spring data and a couchbase behind in a spring boot app.
Here are the fieldmapping:
#Field
private LocalDateTime start;
#Field
private LocalDateTime end;
When I save the object then the dates are stored as numbers in couchbase.
Here are the stored data in couchbase:
"start": 1518818215508,
So the problem is, if I store an LocalDateTime e.g at 10.00, and then read it from db the result is 09:00 instead of 10:00 because of my local time +1:00.
In Postgres I would save the date in an column with mapping: columnDefinition= "TIMESTAMP WITH TIME ZONE"
How I can solve this problem in couchbase?
JSON (famously) has no date format (unlike relational databases which have a sprawling number of different formats). If you want to store timezone data in JSON, here are two options I can think of:
Using a string instead of a number, and then using something like ISO-8601.
Store the epoch time as you currently are as a UTC value, but also store a separate number field that represents a timezone offset from UTC
I would recommend going with the first approach.
I'm no Spring/Java expert, but a quick look at the documentation says you can do this by setting system property org.springframework.data.couchbase.useISOStringConverterForDate to true

Informix JDBC timestamp string format

I have Informix database with timestamp field defined as YEAR TO SECOND.
When I show this field using JDBC rs.getString(column) it uses format with miliseconds so this field looks like:
2008-12-18 13:58:14.0
I would like it to use only YEAR TO SECOND fields. I set environment variable:
GL_DATETIME=%Y-%m-%D %H:%M:%S
but even then I got miliseconds. Programs using ODBC do not show milisecond. How can I receive TIMESTAMP string "YEAR TO SECOND" only? In my program I can check metadata if field is TIMESTAMP and then cut ".0", but I think there should be simplier way.
Server version:
IBM Informix Dynamic Server Version 11.50.TC2DE
Client version:
IBM Informix JDBC Driver for IBM Informix Dynamic Server 3.50.JC3DE
EDIT
It looks that all other JDBC drivers I tested (Oracle and PostgreSQL) shows Timestamp columns with miliseconds if I use getString(). So I used solution proposed by Todd. I check metatdata and if column is Timestamp then I use getTimestamp() and format it.
If you are using JDBC, you can use the rs.getDate(column) or rs.getTimestamp(column) methods, which return Date and Timestamp objects respectively. Then you have an object representing time, rather than a String expressing it directly. With Date or Timestamp, you can use a date formatter to format it to whatever String representation of that time you choose.
Update (after reading comments below):
If you use getDate(), it will still work for Timestamp columns. It will just reduce the precision down to the second. That way you don't have to check the metadata, you just have to know that the column is some kind of timestamp or date.

Resources