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
Related
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());
Hi i am trying to get the current year in the below code however it is returning a 1970 year instead of 2020 last month this was working correctly but since we in January 2020, it is now returning a date from 1970, please assist
public String firstDateOfNextMonth(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar today = Calendar.getInstance();
Calendar next = Calendar.getInstance();
today.clear();
Date date;
next.clear();
next.set(Calendar.YEAR, today.get(Calendar.YEAR));
next.set(Calendar.MONTH, today.get(Calendar.MONTH)+ 1);
next.set(Calendar.DAY_OF_MONTH, 1);
date = next.getTime();
Log.d(TAG, "The Date: " + dateFormat.format(date));
return dateFormat.format(date);
}
If you have Java 8 or above, then you have java.time and you won't have to rely on outdated datetime implementations and you can do it this way:
public static String getFirstOfNextMonth() {
// get a reference to today
LocalDate today = LocalDate.now();
// having today,
LocalDate firstOfNextMonth = today
// add one to the month
.withMonth(today.getMonthValue() + 1)
// and take the first day of that month
.withDayOfMonth(1);
// then return it as formatted String
return firstOfNextMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
which prints the following when called today (2020-01-03) like System.out.println(getFirstOfNextMonth());:
2020-02-01
You might have to involve an external library, the ThreeTenAbp if you want it to work in Android below API level 26. Its use is explained in this question.
not sure why the today date gets cleared, remove today.clear() at line 4
today.clear(); initalize all elements of a date with the value 0
removing this line will give you the right answer
tl;dr
LocalDate // Represent a date-only value without a time-of-day and without a time zone.
.now( // Determine the current date as seen through the wall-clock time used by people in certain region (a time zone).
ZoneId.of( "America/Montreal" ) // Real time zone names have names in the format of `Continent/Region`. Never use 2-4 letter pseudo-zones such as `IST`, `PST`, or `CST`, which are neither standardized nor unique.
) // Return a `LocalDate`.
.with( // Move from one date another by passing a `TemporalAdjuster` implementation.
TemporalAdjusters // Class providing several implementations of `TemporalAdjuster`.
.firstDayOfNextMonth() // This adjuster finds the date of the first of next month, as its name suggests.
) // Returns another `LocalDate` object. The original `LocalDate` object is unaltered.
.toString() // Generate text in standard ISO 8601 format of YYYY-MM-DD.
See this code run live at IdeOne.com.
2020-02-01
Details
You are using terrible date-time classes that were made obsolete years ago by the unanimous adoption of JSR 310 defining the java.time classes.
The Answer by deHaar is correct. Here is an even shorter solution.
TemporalAdjuster
To move from one date to another, the java.time classes include the TemporalAdjuster interface. Pass one of these objects to the with method found on many of the other java.time classes.
TemporalAdjusters.firstDayOfNextMonth()
Several implementations of that interface are found in the class TemporalAdjusters (note the s plural). One of those is firstDayOfNextMonth(), just what you need.
Get today's date. A time zone is required, as for any given moment the date varies around the globe by time zone. If omitted, your JVM's current default time zone is implicitly applied. Better to be explicit.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;
Get your TemporalAdjuster object.
TemporalAdjuster ta = TemporalAdjusters.firstDayOfNextMonth() ;
Apply that adjuster to get another LocalDate object. Note that java.time classes are immutable by design. So we get a new object rather than altering the original.
LocalDate firstOfNextMonth = today.with( ta ) ;
We can shorten this code to a one-liner, if desired.
LocalDate firstOfNextMonth =
LocalDate
.now(
ZoneId.of( "Africa/Tunis" )
)
.with(
TemporalAdjusters.firstDayOfNextMonth()
)
;
Text
Your desired output format of YYYY-MM-DD complies with the ISO 8601 standard used by default in the java.time classes when parsing/generating text. So no formatting pattern need be specified.
String output = firstOfNextMonth.toString() ;
2020-02-01
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.
You are using Calendar.clear() which clears all the fields of your calendar, and essentially reverts it to 1/1/1970 (epoch time 0).
remove today.clear() and you'll get the correct answer
see more here
Remove next.clear();. As Calendar next= Calendar.getInstance(); initiates next with the current date, in your cases Fri Jan 03 2020 15:07:53. And when you do next.clear(), it sets to the inital epoch.
Epoch, also known as Unix timestamps, is the number of seconds (not
milliseconds!) that have elapsed since January 1, 1970 at 00:00:00 GMT
(1970-01-01 00:00:00 GMT).
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());
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());
actually I'm a .NET guy and I wonder why such a simple and trivial things as handling date/time objects is that complicated
Everything I need is a object which holds the parameters for Day, Month, Year, Hour, Minute, Second...
and the possibility to manipulate theses values.
I don't want any conversion to any timezone.
Values of parameter should have the value is set!
Question 1:
How to create a date object from minutes?
Question 2:
How to create a date object from int's??
I've already spend hours to accomplish that and I can't believe that I really have to create my own DateTime implementation in Java!!
I tried it using Calendar(GMC, UTC...) and just Date but always the same.
The values got from my Date-TimePicker are transformed to daylight saving time or some other rule corresponding to the calender I defined.
One thing I really wonder about is that my time also get transformed when I use just "Date" object...
Cheers,
Stefan
I wonder why such a simple and trivial things as handling date/time objects is that complicated
The information technology industry as a whole went decades without tackling the surprisingly tricky problem of date-time handling.
Java originally inherited some code provided by Taligent/IBM. These became the java.util.Date,Calendar, GregorianCalendar, and related classes. They are terrible, bloody awful, flawed in design, and not object-oriented.
The Joda-Time project led by Stephen Colebourne was the first attempt I know of to tackle the date-time problem in a robust and competent manner. Later, Colebourne et al. took the lessons learned there to lead JSR 310, the java.time implementation, and related projects, the back-port in ThreeTen-Backport, and further additional functionality in ThreeTen-Extra.
So now Java has the industry-leading framework for date-time work in the java.time classes.
object which holds the parameters for Day, Month, Year, Hour, Minute, Second... and the possibility to manipulate theses values.
For a date-only, use LocalDate. For a date with time-of-day but lacking the context of a known offset-from-UTC or time zone, use LocalDateTime (not a moment). For a moment, a specific point on the timeline, use Instant (always in UTC), OffsetDateTime (a date with time-of-day in the context of a certain number of hours-minutes-seconds ahead/behind the prime meridian), or ZonedDateTime (a date and time with a time zone assigned).
Question 1: How to create a date object from minutes?
Not sure what you mean.
To represent a span-of-time unattached to the timeline, use Duration.
Duration d = Duration.ofMinutes( 10 ) ;
Instant now = Instant.now() ;
Instant tenMinutesFromNow = now.plus( d ) ;
If you have a count of minutes into the day, use LocalTime.MIN (00:00:00) with a Duration.
Duration d = Duration.ofMinutes( 10 ) ;
LocalTime lt = LocalTime.MIN.plus( d ) )
Question 2: How to create a date object from int's??
I am guessing you mean you want specify the year, month, day, and so on as a series of numbers. For that, use the LocalDateTime factory methad.
LocalDateTime ldt = LocalDateTime.of( 2020 , 1 , 23 , 15 , 30 , 0 , 0 ) ; // year, month, day, hour, minute, second, nanos fraction of second.
Or build up from a LocalDate and LocalTime.
LocalDate ld = LocalDate.of( 2020 , 1 , 23 ) ;
LocalTime lt = LocalTime.of( 15 , 30 ) ;
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
As mentioned above, a LocalDateTime cannot represent a moment. To determine a moment, specify a time zone. For example, in our code above, do you mean 3:30 PM in Tokyo, Toulouse, or Toledo — thee different moments, several hours apart.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust into UTC by extracting a Instant.
Instant instant = zdt.toInstant() ;
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.
Date and Calendar are not the best APIs in Java's library (to put it mildly, I consider them flaw-complementary), that's why a lot of Java programmers are using Joda-Time and many are looking forward to the inclusion in the standard distribution of JSR-310, a brandnew replacement for the old Date & Calendar mess. Joda has the added benefit that transitioning between Date and Joda's types is very easy (by using .toDate() or by using the relevant constructor that accepts a Date) so that using Joda's types inside your code and Date just at the "outer edges" where you interact with Date based code is not painful at all.
For your question 2, there's still a Date constructor that accepts int, and although it's deprecated you can still use it, see this thread. But I'd only suggest you take that route if switching to Joda isn't an option for you.
I suggest that you take a look at Joda Time, it's java dates designed right.