Java utc milliseconds - java

Trying to get Universal Time in java seems to be so difficult. Something like this in C#
DateTime.Now.ToUniversalTime()
seems to be something so difficult. I have code that subtracts a current utc time from a earlier date that is also utc to find the difference in time. But I can't seem to see how to get the current utc time. this is my current code
Date date = new Date();
long difference = date.getTime() - s.getTime();
s is already in utc time because it comes from a source that is passing me the utc time

tl;dr
Current moment in UTC:
Instant.now()
Elapsed time:
Instant then = … ;
Instant now = Instant.now();
Duration duration = Duration.between( then , now ); // For days-hours-minutes-seconds scale.
Render as a count of milliseconds.
long millis = duration.toMillis(); // Possible data-loss in truncating nanoseconds to milliseconds.
java.time
The modern approach to date-time handling in Java is the java.time classes.
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).
Instant instant = Instant.now(); // Current moment in UTC.
The Duration class represents a span of time unattached to the timeline. You can feed in a pair of Instant objects to calculate the number of days, hours, minutes, seconds, and nanoseconds in between.
Duration duration = Duration.between( thisInstant , thatInstant );
Call toString to generate a string in standard ISO 8601 format of PnYnMnDTnHnMnS where P marks the beginning and T separates any years-months-days from the hours-minutes-seconds. For example, an hour and a half is PT1H30M.
You can get the total number of milliseconds in this duration. But beware of possible data-loss. The Instant and Duration classes work in a resolution of nanoseconds, much finer than milliseconds. So extracting milliseconds will truncate any fraction of a second beyond the milliseconds. In other words, rather than having a split second with a decimal representation of up to nine digits, you will have only up to three digits.
long millis = duration.toMillis(); // Possible data-loss in truncating nanoseconds to milliseconds.
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 java.time.
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….
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.
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to java.time. Leaving this section intact for history.
Using the Joda-Time 2.4 library.
DateTime nowUtc = DateTime.now( DateTimeZone.UTC );
Best to avoid java.util.Date and .Calendar as they are notoriously troublesome. But if you must, you can convert.
Date date = nowUtc.toDate();
As for getting a difference between date-time values, search StackOverflow for hundreds of answers. Joda-Time offers 3 classes for representing a span of time: Interval, Period, and Duration.

Give this a try:
Date utcDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
Best,
Loddi

Hmm, no one mentioned System.currentTimeMillis() so i will :) This will return the number of millis since the Unix epoch. This will always be in UTC (e.g. if you call it at the same time in London and in Athens you will get the same values - if the times are set correctly on those devices the timezone shouldn't matter). If you want to obtain a Calendar instance from a number of millis you can just do something like:
Calendar cal = GregorianCalendar.getInstance();
cal.setTimeInMillis(yourMillis);

You can use follwing method to find UTC time:
Calender c= Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Then you can get month,day ,time ,year ant from the calender object..
ex: c.get(Calender.YEAR)
Hope this will help you..

Date is in UTC. There's no time zone attached to Date.
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
What makes you think it's in local time?
Edit: The documentation does say this, so maybe that's the problem:
Although the Date class is intended to reflect coordinated universal
time (UTC), it may not do so exactly, depending on the host
environment of the Java Virtual Machine.
It looks like this might be a good solution:
Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;

Related

How to convert Hex String into Date [duplicate]

I need to convert a unix timestamp to a date object.
I tried this:
java.util.Date time = new java.util.Date(timeStamp);
Timestamp value is: 1280512800
The Date should be "2010/07/30 - 22:30:00" (as I get it by PHP) but instead I get Thu Jan 15 23:11:56 IRST 1970.
How should it be done?
For 1280512800, multiply by 1000, since java is expecting milliseconds:
java.util.Date time=new java.util.Date((long)timeStamp*1000);
If you already had milliseconds, then just new java.util.Date((long)timeStamp);
From the documentation:
Allocates a Date object and
initializes it to represent the
specified number of milliseconds since
the standard base time known as "the
epoch", namely January 1, 1970,
00:00:00 GMT.
java.time
Java 8 introduced a new API for working with dates and times: the java.time package.
With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant.
Instant instant = Instant.ofEpochSecond( timeStamp );
If you need a java.util.Date to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.
Date date = Date.from( instant );
This is the right way:
Date date = new Date ();
date.setTime((long)unix_time*1000);
tl;dr
Instant.ofEpochSecond( 1_280_512_800L )
2010-07-30T18:00:00Z
java.time
The new java.time framework built into Java 8 and later is the successor to Joda-Time.
These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.
Instant instant = Instant.ofEpochSecond( 1_280_512_800L );
instant.toString(): 2010-07-30T18:00:00Z
See that code run live at IdeOne.com.
Asia/Kabul or Asia/Tehran time zones ?
You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or IRST as they are not true time zones, not standardized, and not even unique(!).
If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.
ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z ); // Same moment, same point on timeline, but seen as different wall-clock time.
2010-07-30T22:30+04:30[Asia/Tehran]
Converting from java.time to legacy classes
You should stick with the new java.time classes. But you can convert to old if required.
java.util.Date date = java.util.Date.from( instant );
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).
DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );
Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.
java.util.Date date = dateTime.toDate();
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, 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.
Looks like Calendar is the new way to go:
Calendar mydate = Calendar.getInstance();
mydate.setTimeInMillis(timestamp*1000);
out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));
The last line is just an example how to use it, this one would print eg "14.06.2012".
If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.
If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Date's constructor expects the timeStamp value to be in milliseconds.
Multiply your timestamp's value with 1000, then pass it to the constructor.
If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;
The above decriptions will result different Date values, if you run with EST or UTC timezones.
To set the timezone; aka to UTC,
you can simply rewrite;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));
For kotlin
fun unixToDate(timeStamp: Long) : String? {
val time = java.util.Date(timeStamp as Long * 1000)
val sdf = SimpleDateFormat("yyyy-MM-dd")
return sdf.format(time)
}
Sometimes you need to work with adjustments.
Don't use cast to long! Use nanoadjustment.
For example, using Oanda Java API for trading you can get datetime as UNIX format.
For example: 1592523410.590566943
System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
System.out.println("instant = " + Instant.ofEpochSecond(1592523410));
you get:
instant with nano = 2020-06-18T23:36:50.590566943Z
instant = 2020-06-18T23:36:50Z
Also, use:
Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );
LocalDateTime is another choice, like:
LocalDateTime.ofInstant(Instant.ofEpochSecond(unixtime), ZoneId.systemDefault())
Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());

Java Date return 1970? [duplicate]

I need to convert a unix timestamp to a date object.
I tried this:
java.util.Date time = new java.util.Date(timeStamp);
Timestamp value is: 1280512800
The Date should be "2010/07/30 - 22:30:00" (as I get it by PHP) but instead I get Thu Jan 15 23:11:56 IRST 1970.
How should it be done?
For 1280512800, multiply by 1000, since java is expecting milliseconds:
java.util.Date time=new java.util.Date((long)timeStamp*1000);
If you already had milliseconds, then just new java.util.Date((long)timeStamp);
From the documentation:
Allocates a Date object and
initializes it to represent the
specified number of milliseconds since
the standard base time known as "the
epoch", namely January 1, 1970,
00:00:00 GMT.
java.time
Java 8 introduced a new API for working with dates and times: the java.time package.
With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant.
Instant instant = Instant.ofEpochSecond( timeStamp );
If you need a java.util.Date to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.
Date date = Date.from( instant );
This is the right way:
Date date = new Date ();
date.setTime((long)unix_time*1000);
tl;dr
Instant.ofEpochSecond( 1_280_512_800L )
2010-07-30T18:00:00Z
java.time
The new java.time framework built into Java 8 and later is the successor to Joda-Time.
These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.
Instant instant = Instant.ofEpochSecond( 1_280_512_800L );
instant.toString(): 2010-07-30T18:00:00Z
See that code run live at IdeOne.com.
Asia/Kabul or Asia/Tehran time zones ?
You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or IRST as they are not true time zones, not standardized, and not even unique(!).
If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.
ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z ); // Same moment, same point on timeline, but seen as different wall-clock time.
2010-07-30T22:30+04:30[Asia/Tehran]
Converting from java.time to legacy classes
You should stick with the new java.time classes. But you can convert to old if required.
java.util.Date date = java.util.Date.from( instant );
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).
DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );
Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.
java.util.Date date = dateTime.toDate();
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, 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.
Looks like Calendar is the new way to go:
Calendar mydate = Calendar.getInstance();
mydate.setTimeInMillis(timestamp*1000);
out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));
The last line is just an example how to use it, this one would print eg "14.06.2012".
If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.
If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Date's constructor expects the timeStamp value to be in milliseconds.
Multiply your timestamp's value with 1000, then pass it to the constructor.
If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;
The above decriptions will result different Date values, if you run with EST or UTC timezones.
To set the timezone; aka to UTC,
you can simply rewrite;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));
For kotlin
fun unixToDate(timeStamp: Long) : String? {
val time = java.util.Date(timeStamp as Long * 1000)
val sdf = SimpleDateFormat("yyyy-MM-dd")
return sdf.format(time)
}
Sometimes you need to work with adjustments.
Don't use cast to long! Use nanoadjustment.
For example, using Oanda Java API for trading you can get datetime as UNIX format.
For example: 1592523410.590566943
System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
System.out.println("instant = " + Instant.ofEpochSecond(1592523410));
you get:
instant with nano = 2020-06-18T23:36:50.590566943Z
instant = 2020-06-18T23:36:50Z
Also, use:
Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );
LocalDateTime is another choice, like:
LocalDateTime.ofInstant(Instant.ofEpochSecond(unixtime), ZoneId.systemDefault())
Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());

user defined datetime input in java [duplicate]

This question already has answers here:
How to find the duration of difference between two dates in java?
(18 answers)
Closed 4 years ago.
i wanted to take an input of date and time in the below format and need to calculate the time difference between two, can anyone suggest how to take below string as input and calculate the time difference.
user defined datetime input in java
String startTime= "11/27/2018+09:00:00";
String endTime= "11/28/2018+13:00:00";
The + is a separator (not a sign as in plus or minus).
Senseless input
String startTime= "11/27/2018+09:00";
String endTime= "11/28/2018+13:00";
These inputs do not make sense. Applying an offset-from-UTC such as +09:00 to a date such as 11/27/2018 has no meaning.
For an offset to have meaning, you need a date and a time-of-day.
We can make a guess and assume the people sending the data meant the first moment of the day. If so, they should have said so by including that in the data.
The trick here is that some dates in some time zones do not always start at 00:00:00 time-of-day. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00. Unfortunately, your input has only an offset (a number of hours-minutes-seconds) rather than a time zone (Continent/Region name). A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. Without a time zone, we cannot look up the rules to know the anomalies.
The best you could do is assume the day starts at 00:00:00 and ignore the reality of any anomalies. But this is guesswork and inadvisable. The real solution is to educate the publisher of your data about two things when exchanging date-time values: (a) Use UTC rather than an offset or zone, and (b) write strings in standard ISO 8601 format.
Guesswork
If correcting the source of this data is not feasible, then we can plod on with guesswork.
Extract the date, separate from offset.
String input = "11/27/2018+09:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu" );
LocalDate localDate = LocalDate.parse( input.substring( 0 , 10 ) , f );
ZoneOffset zoneOffset = ZoneOffset.of( input.substring( 11 ) );
localDate.toString(): 2018-11-27
zoneOffset.toString(): +09:00
OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , zoneOffset );
2018-11-27T00:00+09:00
We can calculate elapsed time as a Duration. But beware, without the context of time zones, we cannot account for any anomalies that may be occurring in this time period, as discussed above. With only offsets rather than zones, calculations are made using generic 24-hour days. So, again, this is just sloppy guesswork, not a reliable solution.
Duration d = Duration.between( odt , odtLater ) ;
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.
In java 8 there is:
LocalDateTime: use this if you need to deal with date and time.
LocalDate: use this if you need to deal with date only.
ZonedDateTime: use this if you need to deal with date time with time zone.
OffsetDateTime: use this if you need to deal with date time with offset. (the most suitable for your case)
Your case is only use Date and Offset, it's a bit tricky since time zone and offset can only be applied to LocalDateTime (not only date).
However, I think you can solved it like this:
Create a method that convert your date string into OffsetDateTime like this:
private static OffsetDateTime createZonedDateTime (String dateWithTimeOffset)
{
//TODO: assert that dateWithTimeOffset is valid
String date = dateWithTimeOffset.substring (0, 10);
String timeOffset = dateWithTimeOffset.substring (10, 13);
//define your date pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ("MM/dd/yyyy");
return LocalDate.parse (date, formatter) // create LocalDate
.atStartOfDay () // convert it to LocalDateTime with time 00:00:00
.atOffset (ZoneOffset.of(timeOffset)); // apply the offset
}
Then you can simple create your OffsetDateTime like this:
OffsetDateTime startTime = stringToZonedDateTime ("11/27/2018+09:00");
OffsetDateTime endTime = stringToZonedDateTime ("11/28/2018+13:00");
You can create duration using OffsetDateTime like this:
Duration duration = Duration.between (startTime, endTime);
Duration have everything you need related with time duration, for example:
duration.toHours () // will give you the hour duration

Getting a Date from a GregorianCalendar

The GregorianCalendar is being inconsistent:
Calendar cal = new GregorianCalendar(2000, 0, 1);
long testCalOne = cal.getTimeInMillis();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
long testCalTwo = cal.getTimeInMillis();
Calendar cal2 = new GregorianCalendar(2000, 0, 1);
cal2.setTimeZone(TimeZone.getTimeZone("UTC"));
long testCalThree = cal2.getTimeInMillis();
System.out.println(testCalOne + ", " + testCalTwo + ", " + testCalThree);
Results in
946681200000, 946681200000, 946684800000
This represents 2000-01-01 midnight in GMT+1, GMT+1 and UTC respectively. My timezone is +1 hour relative to UTC.
The problem here is that the getTimeInMillis is supposed to return the amount of milliseconds since 1970-01-01 in UTC. Only testCalThree is correct.
Another problem is that setTimeZone is seemingly not working depending on whether I called getTimeInMillis before.
My goal is to take a Calendar I receive as parameter from other code and get a UTC (java.util) Date for further use.
tl;dr
myGregCal.toZonedDateTime()
.toInstant()
…or…
java.util.Date.from(
myGregCal.toZonedDateTime()
.toInstant()
)
java.time
My goal is to take a Calendar I receive as parameter from other code and get a UTC (java.util) Date for further use.
The troublesome old date-time classes of Calendar and Date are now legacy, supplanted by the java.time classes. Fortunately you can convert to/from java.time by calling new methods on the old classes.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
For UTC value, extract an Instant. That class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = zdt.toInstant() ;
To generate a String representing that UTC value in a standard ISO 8601 format, call toString.
String output = instant.toString() ;
If you need other formats in generated strings, convert to the more flexible OffsetDateTime and use DateTimeFormatter. Search Stack Overflow for many examples.
Best to avoid the Date class. But if you must, convert. Like Instant, Date represents a point on the timeline in UTC. But Date is limited to milliseconds resolution. So you risk data loss, lopping off digits from the decimal fraction of a second beyond the 3 digits of milliseconds versus 9 digits of nanoseconds.
java.util.Date utilDate = Date.from( instant ) ;
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 java.time.
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….
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.
I think it's a bug in the Calendar implementation. time is cached, i.e. if you've calculated it once it is reused unless something changes.
But somehow setting time zone is not recognized as a relevant change.
You can force re-calculation of time in ms by changing or clearing some field explicitly. So this:
Calendar cal = new GregorianCalendar(2000, 0, 1);
long testCalOne = cal.getTimeInMillis();
cal.clear(Calendar.ZONE_OFFSET);
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
long testCalTwo = cal.getTimeInMillis();
Calendar cal2 = new GregorianCalendar(2000, 0, 1);
cal2.setTimeZone(TimeZone.getTimeZone("UTC"));
long testCalThree = cal2.getTimeInMillis();
System.out.println(testCalOne + ", " + testCalTwo + ", " + testCalThree);
Gives:
946681200000, 946684800000, 946684800000
As you would expect. The only thing I had to do is cal.clear(Calendar.ZONE_OFFSET) before setting time zone.
Anyway, I'd like to repeat the recommendation from comments. If you value your sanity, switch to JodaTime or Java8 date/time.
Upon thinking further on it, the code may work as intended. setTimeZone may just function differently depending on whether a getter has been called upon the Calendar or not.
In the first case, it changes the timezone, but because the time has already been gotten and therefore initialized, the UTC time is unchanged.
In the second case, it indicates that the initializing date of 2001-1-1 we passed in the constructor was a UTC time and should be parsed as UTC rather than the local timezone.
If so, then the results make sense.

Wrong timestamp value in Scala [duplicate]

I need to convert a unix timestamp to a date object.
I tried this:
java.util.Date time = new java.util.Date(timeStamp);
Timestamp value is: 1280512800
The Date should be "2010/07/30 - 22:30:00" (as I get it by PHP) but instead I get Thu Jan 15 23:11:56 IRST 1970.
How should it be done?
For 1280512800, multiply by 1000, since java is expecting milliseconds:
java.util.Date time=new java.util.Date((long)timeStamp*1000);
If you already had milliseconds, then just new java.util.Date((long)timeStamp);
From the documentation:
Allocates a Date object and
initializes it to represent the
specified number of milliseconds since
the standard base time known as "the
epoch", namely January 1, 1970,
00:00:00 GMT.
java.time
Java 8 introduced a new API for working with dates and times: the java.time package.
With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant.
Instant instant = Instant.ofEpochSecond( timeStamp );
If you need a java.util.Date to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.
Date date = Date.from( instant );
This is the right way:
Date date = new Date ();
date.setTime((long)unix_time*1000);
tl;dr
Instant.ofEpochSecond( 1_280_512_800L )
2010-07-30T18:00:00Z
java.time
The new java.time framework built into Java 8 and later is the successor to Joda-Time.
These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.
Instant instant = Instant.ofEpochSecond( 1_280_512_800L );
instant.toString(): 2010-07-30T18:00:00Z
See that code run live at IdeOne.com.
Asia/Kabul or Asia/Tehran time zones ?
You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or IRST as they are not true time zones, not standardized, and not even unique(!).
If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.
ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z ); // Same moment, same point on timeline, but seen as different wall-clock time.
2010-07-30T22:30+04:30[Asia/Tehran]
Converting from java.time to legacy classes
You should stick with the new java.time classes. But you can convert to old if required.
java.util.Date date = java.util.Date.from( instant );
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).
DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );
Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.
java.util.Date date = dateTime.toDate();
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, 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.
Looks like Calendar is the new way to go:
Calendar mydate = Calendar.getInstance();
mydate.setTimeInMillis(timestamp*1000);
out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));
The last line is just an example how to use it, this one would print eg "14.06.2012".
If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.
If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Date's constructor expects the timeStamp value to be in milliseconds.
Multiply your timestamp's value with 1000, then pass it to the constructor.
If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;
The above decriptions will result different Date values, if you run with EST or UTC timezones.
To set the timezone; aka to UTC,
you can simply rewrite;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));
For kotlin
fun unixToDate(timeStamp: Long) : String? {
val time = java.util.Date(timeStamp as Long * 1000)
val sdf = SimpleDateFormat("yyyy-MM-dd")
return sdf.format(time)
}
Sometimes you need to work with adjustments.
Don't use cast to long! Use nanoadjustment.
For example, using Oanda Java API for trading you can get datetime as UNIX format.
For example: 1592523410.590566943
System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
System.out.println("instant = " + Instant.ofEpochSecond(1592523410));
you get:
instant with nano = 2020-06-18T23:36:50.590566943Z
instant = 2020-06-18T23:36:50Z
Also, use:
Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );
LocalDateTime is another choice, like:
LocalDateTime.ofInstant(Instant.ofEpochSecond(unixtime), ZoneId.systemDefault())
Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());

Categories

Resources