Java: transform Long Timestamp + int offset to readable format - java

I'm trying to convert a Long timestamp with an offset (int) into a more readable format. So for example I have 1514564669355 as a timestamp with offset equal to 360. How should I go about transforming this into the equivalent date format using java?
In this case the timestamp would be stored in UTC, so with the offset I'm looking to converting it to whatever timezone it needs. Thanks for any help/tips.

Your Question is not clear.
Perhaps you mean you have a value in UTC and want to adjust it to an offset of 360 minutes ahead of UTC. (A poor way to communicate a moment in time.)
Or perhaps you meant the given value is already ahead of UTC. (An even worse way to communicate a moment in time.)
Starting with UTC
First parse your input number. We will assume that number is a count of milliseconds since the first moment of 1970 UTC, 1970-01-01T00:00Z.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochMilli( 1_514_564_669_355L ) ;
instant.toString(): 2017-12-29T16:24:29.355Z
An offset-from-UTC is a number of hours, minutes, and seconds ahead of, or behind, UTC.
Perhaps your Question’s mention of an offset of 360 is meant to be 360 minutes, or 6 hours ahead of UTC.
The ZoneOffset class cannot be instantiated from a number of minutes over 59. So we convert from 360 minutes to a total number of seconds.
int seconds = ( int ) TimeUnit.MINUTES.toSeconds( 360L ) ; // Convert minutes to seconds.
ZoneOffset offset = ZoneOffset.ofTotalSeconds( seconds ); // Determine offset-from-UTC.
offset.toString(): +06:00
Adjust our Instant in UTC to this offset, yielding a OffsetDateTime object. Same moment, same point on the timeline, different wall-clock time. So the time-of-day is seen as 10 PM rather than as 4 PM since ( 16 + 6 ) = 22.
OffsetDateTime odt = instant.atOffset( offset );
odt.toString(): 2017-12-29T22:24:29.355+06:00
Starting with offset
Perhaps you meant the moment being communicated is a count of milliseconds from UTC but then the number of milliseconds in 360 minutes has already been added or subtracted.
By the way, this is a very bad way to exchange date-time values. Educate the supplier of your data about the ISO 8601 standard.
Let's undo that addition/subtraction of an offset, to get back to UTC.
long millisInOffset = TimeUnit.MINUTES.toMillis( 360L ); // Convert minutes to milliseconds.
long millisSinceEpoch = ( 1_514_564_669_355L - millisInOffset );
Instant instant = Instant.ofEpochMilli( millisSinceEpoch );
instant.toString(): 2017-12-29T10:24:29.355Z
See that value in the offset sent to us.
int seconds = ( int ) TimeUnit.MILLISECONDS.toSeconds( millisInOffset );
ZoneOffset offset = ZoneOffset.ofTotalSeconds( seconds );
OffsetDateTime odt = instant.atOffset( offset );
System.out.println( odt );
2017-12-29T16:24:29.355+06:00
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

Android how to get UTC Timezone offset even of negative timezone

Hi I am trying to send the UTC offset towards my server. So I am converting the device time zone into utc offset using following code
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
Log.d("UTC_Offset",offset);
Now i know as I am using the Math.abs it is not giving me the minus values but I am really dumb to know that how could I get the offset of those timezone who are in negative such as Tijuana which is GMT-07:00
Note: I may be wrong about the offset thing in UTC but this solution I found on SO. Please let me know if there is any solution or also correct me if I am wrong in idea and its that UTC could not be in negative
Use SimpleDateFormat to format it for you:
String offset = new SimpleDateFormat("Z").format(new Date());
offset = offset.substring(0, 3) + ":" + offset.substring(3);
↓↓↓↓↓ IGNORE REST OF ANSWER IF IT IS CONFUSING ↓↓↓↓↓
Results when applying to all TimeZones in the Java VM:
-12:00
-11:00
-10:00
-09:30
-09:00
-08:00
-07:00
-06:00
-05:00
-04:00
-03:00
-02:30
-02:00
-01:00
+00:00
+01:00
+02:00
+03:00
+04:00
+04:30
+05:00
+05:30
+05:45
+06:00
+06:30
+07:00
+08:00
+08:45
+09:00
+09:30
+10:00
+10:30
+11:00
+12:00
+12:45
+13:00
+14:00
Java 8 code to print the above:
Instant now = Instant.now();
SimpleDateFormat fmt = new SimpleDateFormat("Z");
ZoneId.getAvailableZoneIds().stream()
.map(z -> ZoneId.of(z).getRules().getOffset(now))
.distinct()
.sorted(Comparator.reverseOrder())
.forEach(z -> {
fmt.setTimeZone(TimeZone.getTimeZone(z));
String offset = fmt.format(Date.from(now));
offset = offset.substring(0, 3) + ":" + offset.substring(3);
System.out.println(offset);
});
tl;dr
how could I get the offset of those timezone who are in negative such as Tijuana which is GMT-07:00
ZoneId.of( "America/Tijuana" ).getRules().getOffset( Instant.now() ).getTotalSeconds()
-25200
No need to do the math yourself. We have classes for this: java.time.
For older Java before Java 8, use the ThreeTen-Backport library.
For older Android, see the ThreeTenABP project.
Avoid Date, Calendar, SimpleDateFormat, and TimeZone legacy classes.
Example:
org.threeten.bp.ZoneId
.systemDefault()
.getRules()
.getOffset​(
Instant.now()
)
.toString()
To get total seconds of that offset, call ZoneOffset::getTotalSeconds.
java.time
The modern approach uses the modern java.time classes. You are using terrible date-time classes that were years ago supplanted by java.time.
Get the offset-from-UTC of the computer’s current default time zone.
ZoneId z = ZoneId.systemDefault() ;
ZoneRules rules = z.getRules() ;
ZoneOffset offset = rules.getOffset( Instant.now() ) ;
Notice that we passed a moment, represented as Instant object (a moment as seen in UTC). Politicians frequently change the offset used by the zone(s) of their jurisdiction. So the offset of your zone is likely to change over time. So you must specify a moment to ask for the offset that was in effect at that point in time.
Generate text representing that offset, using standard ISO 8601 format.
String output = offset.toString() ;
-07:00
When receiving such text, you can parse as a ZoneOffset object.
ZoneOffset offset = ZoneOffset.parse( "-07:00" ) ;
You asked:
that UTC could not be in negative
An negative offset means a place whose clocks run behind UTC. Generally, this means west (left) of the prime meridian, such as the Americas.
A positive offset means a place whose clocks run ahead of UTC. Generally, this means east (right) of the prime meridian, such as Europe, Africa, Asia.
Well, this is the commonly used meaning of positive & negative offsets, defined in the ISO 8601 standard. Some protocols and industries may use the opposite meaning. Always understand the intention of any data source you may be using.
how could I get the offset of those timezone who are in negative such as Tijuana which is GMT-07:00
ZoneId z = ZoneId.of( "America/Tijuana" ) ;
ZoneRules rules = z.getRules() ;
ZoneOffset offset = rules.getOffset( Instant.now() ) ;
String output = offset.toString() ;
System.out.println( output ) ;
See this code run live at IdeOne.com.
-07:00
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Negative Values when calculating time of a java date

just a question what i am doing wrong. I have this code:
public static int berechneSekundenwert(String datum, String zeit) throws ParseException {
Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat( "dd.MM.yyyy HH:mm:ss" );
dt = df.parse( datum+" "+ zeit);
int gesamtzeit = (int)dt.getTime();
return gesamtzeit;
}
Now my import format is:
09.11.2019 01:30:17
What i want to do is calculate the time passed for these dates, so i
can later sort them by time. But i get negative values?!
Example output (passed time, date, daytime):
-2120215336 30.09.2019 12:03:35
1757321960 25.09.2019 16:06:25
-2111322336 30.09.2019 14:31:48
-1281127040 21.08.2019 12:05:36
-1280681040 21.08.2019 12:13:02
377782960 09.09.2019 16:54:06
1301386664 09.11.2019 01:30:17
710621960 13.09.2019 13:21:25
712564960 13.09.2019 13:53:48
Shouldn't they all be positive, since java states, that the getTime function measures the time since 01.01.1970
Anyone knows what i did wrong?
Computers use something called a timestamp to represent dates. In Java, Date::getTime() returns the milliseconds passed since 1970-01-01T00:00:00.000Z up to the date in question as long (64-bit integer).
In the code presented, this value is narrowed down to an int (32-bit integer). By narrowing the long to an int, the highest 32 bits get cut of. The largest value representable by an int is 2^31 - 1. A quick calculation shows that:
(2^31 - 1) (milliseconds)
/ 1000 (milliseconds per second)
/ 60 (seconds per minute)#
/ 60 (minutes per hour)
/ 24 (hours per day)
= 24.8551348032 (days)
This means that after roughly 25 days, the int will overflow (as it is defined in the Two's compliment). Not to mention that a later point in time could have a lower value than an earlier point in time, thus the negative values.
To fix this issue1, I would suggest to define gesamtzeit as long.
Two remarks on your code:
java.util.Date is regarded as outdated. I would suggest to use java.time.Instant instead.
I would suggest to use English in the source code, only exception being you use domain-specific words that cannot (well) be translated to English.
1 This is only a temporary fix. All representation with a fixed number of bits will eventually overflow. In fact, all representation with any memory constraint at all will overflow eventually. I leave it up to the reader to find out when a 64-bit integer will overflow
tl;dr
See correct Answer by Turing85 about 32-bit versus 64-bit integers.
Use only modern java.time classes, never Date/SimpleDateFormat.
Consider the crucial issue of time zone or offset-from-UTC.
Educate the publisher of your data about the importance of (a) including zone/offset info, and (b) using ISO 8601 standard formats.
Code:
LocalDateTime.parse(
"09.11.2019 01:30:17" ,
DateTimeFormatter.ofPattern( "dd.MM.uuuu HH:mm:ss" )
)
.atOffset(
ZoneOffset.UTC
)
.toInstant()
.toEpochMilli()
See this code run live at IdeOne.com.
1573263017000
Details
The correct Answer by Turing85 addresses your specific question as to why the invalid negative numbers. But you have other problems.
ISO 8601
Now my import format is: 09.11.2019 01:30:17
I suggest you educate the publisher of this data about the ISO 8601 standard defining formats to use when communicating date-time values as text.
Legacy date-time classes
You are use terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310. Never use Date or SimpleDateFormat.
Moment
Apparently you want to get a count of milliseconds since the epoch reference of first moment of 1970 in UTC. But doing that requires a moment, a specific point on the timeline.
Your input does not meet this requirement. Your input is a date and a time-of-day but lacks the context of an offset-from-UTC or a time zone.
So, take your example of 09.11.2019 01:30:17. We cannot know if this is 1:30 in the afternoon of Tokyo Japan, or 1:30 PM in Paris France, or 1:30 in Toledo Ohio US — which are all very different moments, several hours apart on the timeline.
So we must first parse your input as a LocalDateTime. This class represent a date and time without any concept of offset or zone.
String input = "09.11.2019 01:30:17" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Perhaps you know for certain the offset or zone intended by the publisher of this data. If so:
Suggest to the publisher of this data that they include the zone/offset info within their data.
Apply a ZoneOffset to get an OffsetDateTime, or a ZoneId to get a ZonedDateTime.
Perhaps you know for certain this input was intended for UTC, that is, an offset of zero hours-minutes-seconds.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
To get a count of milliseconds since 1970-01-01T00:00Z convert to the basic building-block class Instant.
Instant instant = odt.toInstant() ;
Interrogate for a count of milliseconds since epoch.
long millisSinceEpoch = instant.toEpochMilli() ;
Understand that your original code ignored the crucial issue of time zone & offset-from-UTC. So your code implicitly applies the JVM's current default time zone. This means your results will vary at runtime, and means you likely have incorrect results too.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
why you downcast the return value ofgetTime()?
just make you method return long instead of int
and replace this line
int gesamtzeit = (int)dt.getTime();
with
long gesamtzeit = dt.getTime();

Rrule Until tag data value

I'm working on a project which takes rrule to generate next occurrences. But I'm not able to understand what i need to put in UNTIL tag of rrule.
String str="RRULE:FREQ=MONTHLY;UNTIL=20190625T000000Z;INTERVAL=2;";
Idk how to convert date into "20190625T000000Z".I'm using rfc 2445 java library. If user enters the date as a string for example :25/06/2019......i need to set this value in UNTIL tag as shown above. If I set the default value in UNTIL then it works but not when i make it user friendly.. I'm taking all the values from user as start date, end date, interval, Byday,Until... But idk what value to set in UNTIL.
If someone can help.. Thanks in advance.
Parsing basic ISO 8601 format
Your input 20190625T000000Z is the “basic” variation of standard ISO 8601 format to represent a moment in UTC. The word “basic” means minimizing the use of delimiters (I do not recommend this, as it makes the string less readable by humans).
Defining a formatting pattern to match input.
String input = "20190625T000000Z";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmssX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
Dump to console.
System.out.println("odt.toString(): " + odt);
See this code run live at IdeOne.com.
odt.toString(): 2019-06-25T00:00Z
Translating date to moment
If user enters the date as a string for example :25/06/2019......i need to set this value in UNTIL tag as shown above
First, parse that input string into a LocalDate, representing a date-only value, without time-of-day and without time zone.
DateTimeFormatter fDateOnly = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "25/06/2019" , fDateOnly );
ld.toString(): 2019-06-25
As for translating that date into a moment (a date with time-of-day in a zone or offset-from-UTC), that is trickier than it sounds intuitively.
A date such as the 25th of June 2019 represents an entire day. And a theoretical date at that. The moments when a day begins and ends varies around the globe by time zone. A new day begins much earlier in Tokyo Japan than in Paris France, and even later in Montréal Québec.
Another issue is that the day does not always begin at 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the first moment of a day on some dates in some zones may be something like 01:00:00. Let the java.time classes determine first moment.
ZoneId z = ZoneId.of( "Africa/Tunis" );
ZonedDateTime zdt = ld.atStartOfDay( z );
zdt.toString(): 2019-06-25T00:00+01:00[Africa/Tunis]
That ZonedDateTime object represents a specific moment. But it uses the wall-clock time adopted by the people of a particular region (a time zone). Your goal is a moment in UTC. Fortunately, we can adjust from the zone to UTC by converting to an OffsetDateTime (a date and time with a context of offset-from-UTC rather than a time zone). We can specify UTC (an offset of zero) by the ZoneOffset.UTC constant.
OffsetDateTime odt = zdt.toOffsetDateTime().withOffsetSameInstant( ZoneOffset.UTC );
odt.toString(): 2019-06-24T23:00Z
Note how 00:00 on the 25th in Tunisia is 11 PM “yesterday” the 24th in UTC. Same moment, same simultaneous point on the timeline, but two different wall-clock times.
Lastly, we need a string in that “basic” ISO 8601 format. Use the same formatter we defined above.
DateTimeFormatter fIso8601DateTimeBasic = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmssX" );
String output = odt.format( fIso8601DateTimeBasic );
output: 20190624T230000Z
See this code run live at IdeOne.com.
Just what is the difference between a time zone and an offset-from-UTC? An offset is merely a number of hours-minutes-seconds. Nothing more, nothing less, just a number (well, three numbers). A time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region. For example, in most of North America, the offset changes twice a year, springing ahead an hour and then falling back an hour (the lunacy of Daylight Saving Time (DST)).
Tip: Date-time handling is surprisingly tricky and slippery. If you are working with calendars and the iCalendar spec for data exchange, I suggest you take a long while to study the concepts and practice with the industry-leading java.time classes.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Postgres convert date time difference into HH:MM:SS

Ex:
startTime-EndTime
Diff is 0 years 0 months 5 days 20 hours 6 minutes 30 seconds. I want to convert this into HH:MM:SS format : 120:06:30.
tl;dr
Duration // Represent a span-of-time in terms of total number of whole seconds plus a fractional second in nanos.
.between( // Calculate elapsed time.
myResultSet.getObject( … , OffsetDateTime.class ) , // Start
myResultSet.getObject( … , OffsetDateTime.class ) , // Stop
) // Returns a `Duration` object.
.toString() // Generate text in standard ISO 8601 format of `PnYnMnDTnHnMnS`.
java.time
Doing it on the Java side is simple with a column of a data type akin to the SQL-standard TIMESTAMP WITH TIME ZONE and driver compliant with JDBC 4.2 or later (for support of the modern java.time classes).
OffsetDateTime
Retrieve your moments as OffsetDateTime objects, per JDBC 4.2 spec.
OffsetDateTime start = myResultSet.getObject( … , OffsetDateTime.class ) ;
OffsetDateTime stop = myResultSet.getObject( … , OffsetDateTime.class ) ;
Duration
Calculate elapsed time as a Duration object.
Duration d = Duration.between( start , stop ) ;
ISO 8601
Generate a standard ISO 8601 string of the format PnYnMnDTnHnMnS where the P marks the beginning (probably stands for “period” – no standardized terms in date-time handling unfortunately), and the T separates years-months-days from hours-minutes-seconds. So an hour and a half would be PT1H30M. Your example of 5 days 20hours 6minutes 30 seconds would be P5DT20H6M30S.
The java.time classes use the ISO 8601 format by default. So you generate text by simply calling toString. No need to specify a formatting pattern.
String output = d.toString() ;
P5DT20H6M30S
To parse, call parse.
Duration d = Duration.parse( "P5DT20H6M30S" ) ;
Note that Duration counts days as 24-hour chunks of time, without regard for the calendar. If you want calendar-based dates, use Period class. If you want both concepts together, use PeriodDuration class from the ThreeTen-Extra, but think twice as mixing the two concepts is usually unwise and impractical.
I strongly advise you not represent a span-of-time using the clock notation as shown in your Question. Doing so is ambiguous, error-prone with people misinterpreting the text, as I have personally seen happen in business scenarios. The standard format is much wiser.
Duration::to…Part
But if you insist on the clock-formatting, create a string by calling the to…Part methods on Duration.
String output = d.toDaysPart() + ":" + d.toHoursPart() + ":" + d.toMinutesPart() + ":" + d.toSecondsPart() + "." + d.toNanosPart() ;
toHours versus toHoursPart
If want all the days reported as hours, get total number of hours across entire span-of-time by calling toHours rather than toHoursPart. Then get the parts of minutes and seconds.
Duration d = Duration.between( start , stop ) ;
String output = d.toHours() + ":" + d.toMinutesPart() + ":" + d.toSecondsPart() ;
120:06:30
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
This can be achieved using postgresql.
To compute the difference between two timestamps as a number of seconds, use :
EXTRACT(EPOCH FROM (startTime - endTime))
Then you tun this value back to a timestamp with function TO_TIMESTAMP, and format this as a time using function TO_CHAR.
The hour part is tricky as you want to display values greater than 24 (which, as you would expect, is the maximum allowed in postgres): you need to use a little arithmetics to compute it.
SELECT CONCAT(
EXTRACT(EPOCH FROM (startTime - endTime))/60/60,
':',
TO_CHAR(TO_TIMESTAMP(
EXTRACT(EPOCH FROM (startTime - endTime))
), 'MI:SS')
)
FROM my_table

Weird Date Format To Java Date

I got the following date format that I get from an API (Yes I tried to get them to change the API... dailywtf story):
\/Date(1310481956000+0200)\/
How can I convert this into a Java Date? (java.util.Date)
This comes from a .NET JSON web service.
Without knowing what the date/time string stands for, let me make a guess.
The 1310481956000 looks to be milliseconds after epoch, and the +0200 an offset relative to GMT.
The following code seem to indicate it as well:
final TimeZone tz = TimeZone.getTimeZone("GMT+0200");
final Calendar cal = Calendar.getInstance(tz);
cal.setTimeInMillis(1310481956000L);
final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
f.setTimeZone(tz);
System.out.println(f.format(cal.getTime()));
Prints 2011-07-12 16:45:56 GMT+02:00
How can I convert this into a Java Date? (java.util.Date)
First, get "them" to clearly and precisely tell you exactly what that date format means. (If they won't or can't you could guess; see below.)
Next write a custom parser to parse the String and extract the information content.
Finally, convert the information content into a form that matches one of the Date constructors and create an instance.
My guess is that the 1310481956000 part is the number of milliseconds since the UNIX epoch (1970/01/01T00:00) and that the 0200 represents a timezone offset of 2 hours (MET?). However, you shouldn't rely on a guess. Get "them" to give you the specification, or at least a number of examples and the actual times/timezones that they correspond to.
You'll have to get the format from the API provider but it seems like a epoch + an offset for time zones. To convert it you could try.
final String fromAPI = "1310481956000+0200"
final String epochTime = fromAPI.substring(0, fromAPI.indexOf("+"));
final String timeZoneOffSet = fromAPI.substring(fromAPI.indexOf("+"), fromAPI.size());
Date date = new Date(Long.parseLong(epochTime));
Notice i'm not doing anything with the time zone (if that's what it is). You'll have to deal with that but this should get you on the right path.
tl;dr
Instant.ofEpochMilli(
java.lang.Long.parseLong( "1310481956000" )
).atOffset( ZoneOffset.of( "+0200" ) )
Using java.time
The accepted Answer is correct but outdated. The modern way to handle this is through the java.time classes.
The input is ambiguous. Is it a count from the Unix epoch reference date-time of first moment of 1970 in UTC 1970-01-01T00:00:00:Z and then adjusted by two hours ahead of UTC? If so, this example code seen here works.
First parse that input number as a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Extract the first portion of your string and parse as a long.
long millisSinceEpoch = java.lang.Long.parseLong( "1310481956000" );
Instant instant = Instant.ofEpochMilli( millisSinceEpoch );
instant.toString(): 2011-07-12T14:45:56Z
Extract the last portion of your string and parse as a ZoneOffset.
ZoneOffset offset = ZoneOffset.of( "+0200" );
Apply the offset to the Instant to get an OffsetDateTime.
OffsetDateTime odt = instant.atOffset( offset );
odt.toString(): 2011-07-12T16:45:56+02:00
Note that an offset-from-UTC is not a time zone. A zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
Avoid java.util.Date whenever possible. But if you must use one, you can convert to/from java.time. Look to new conversion methods added to the old classes.
java.util.Date d = java.util.Date.from( odt.toInstant() );
d.toString(): Tue Jul 12 14:45:56 GMT 2011
See live code at IdeOne.com covering this entire example.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories