I know how to get the milliseconds for a date after 1.1.1970. But how can I get the milliseconds for a specific date that occurs before that date?
I need that in an android app.
Thanks!
All numbers are signed in java, so all numbers can be negative. Therefore you can have a date with a negative amount of milliseconds. Therfore dates with a timestamp which is less than 0 is definitely possible.
You can know the earliest possible date by performing:
new Date(Long.MIN_VALUE)
You'll find that this returns a date which is more than 292 million years ago. This is even before the jurassic era. So there really isn't a need to worry about dates before 1970 :)
Using java.time.Instant, get your date in the Instant and you can use the getEpochSecond() method to return the number of seconds before the Epoch and just convert from that.
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html for more details about the Instant class.
tl;dr
LocalDate.of( 1953 , 1 , 17 )
.atStartOfDay( ZoneId.of( "America/Montreal" ) )
.toInstant()
.toEpochMilli()
…yields a negative number:
-535057200000
Details
As the other Answers said:
(a) In representing moments as a count-from-epoch-reference-date, moments before the epoch use negative numbers, moments after the epoch use positive numbers.
(b) You should be using java.time classes rather than the troublesome old date-time classes that are now legacy. See below for info on back-port to Android.
Using java.time
Use LocalDate for a date-only value, with no time-of-day nor time zone.
LocalDate ld = LocalDate.of( 1953 , 1 , 17 );
To convert to a moment, let's get the first moment of the day on that date. That means specifying a time zone, as the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ld.atStartOfDay( z );
Extract an Instant, a moment on the timeline in UTC.
Instant instant = zdt.toInstant();
From the Instant, extract the number of milliseconds since the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00Z). Beware of data-loss, as the java.time classes can hold a moment with a resolution of up to nanoseconds; asking for milliseconds means lopping off any nanoseconds if present.
long epochMillis = instant.toEpochMilli();
See this code run line in IdeOne.com.
ld.toString(): 1953-01-17
zdt.toString(): 1953-01-17T00:00-05:00[America/Montreal]
instant.toString(): 1953-01-17T05:00:00Z
epochMillis: -535057200000
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 problem was something I cannot reproduce. Before 1.1.1970 the values are negative. Now, my program calculates right, but I think, I didn't change something in the code. Maybe it was a cached version, which caused the problems. Thanks for all answers!
Related
In my application i want get some data from server and i should cast date and time!
I receive date and time with this format end_date: "2020-04-08 13:11:14" from server.
I want get now date and time from my device and to calculate with above date (end_date), if this time under 24h i should show for example 15 hour later, but if this time more than 24h i should show 2 days later!
But i don't know how can i it?
Can you help me with send code or send to me other tutorials?!
I searched that but I didn't find anything.
java.time
The modern approach uses java.time classes.
Parse the input string as a LocalDateTime.
To parse, replace the SPACE in the middle with a T to comply with ISO 8601 standard.
String input = "2020-04-08 13:11:14".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Your input lacks an indicator of any time zone or offset-from-UTC. So we do not know if this was meant to be 1 PM in Tokyo Japan, 1 PM in Toulouse France, or 1 PM in Toledo Ohio US. So you cannot reliably compare this to the current date and time.
If you want to presume this string was meant to tell time in your time zone, then assign a time zone to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime then = ldt.atZone( z ) ;
Capture the current moment in the same zone.
ZonedDateTime now = ZonedDateTime.now( z ) ;
Calculate 24 hours later.
ZonedDateTime twentyFourHoursFuture = now.plusHours( 24 ) ;
Compare.
boolean within24Hours = then.isBefore( twentyFourHoursFuture ) ;
Determine elapsed time using the Duration class.
Duration duration = Duration.between( then , now ) ;
If you want to trust the JVM’s current default time zone, call ZoneId.systemDefault. Beware that this default can be changed by other Java code during execution of your app.
ZoneId z = ZoneId.systemDefault() ;
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.
Try using the datetime library, or you can see this answer.
Also if you can choose, it's a good habit to pass the times in UTC from/to the server, it'll save some localization and timezone troubles.
How can I convert incoming long time value in microseconds into milliseconds and then format that to data time stamp as below:
yyyyMMdd-HH:mm:ss.SSS
I am using Java SimpleDateFormat to format the long value to the timestamp. But, converting the microseconds to milliseconds seems problem as I am loosing the value.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HH:mm:ss.SSS");
To convert microsecond to millisecond, I am using the TimeUnit:
long micro //microseconds
long milli = TimeUnit.MILLISECONDS.convert(micro, TimeUnit.MICROSECONDS);
What is the right way to convert the value without loosing any data?
I am using java SimpleDateFormat
Don’t.
Avoid the treacherous old date-time classes bundled with the earliest versions of Java. They were supplanted years ago with the java.time classes when JSR 310 was adopted.
convert incoming long time value in microseconds into milliseconds
Don’t.
The java.time classes use a resolution of nanoseconds, finer than your microseconds. So no need to throw away data.
Instant = ( whole seconds + fractional second as nanos )
Extract the number of whole seconds.
long seconds = TimeUnit.MICROSECONDS.toSeconds( micros ) ;
Get the fractional second, the amount of micros left over after subtracting for the whole seconds.
long microsRemaining =
micros
-
TimeUnit.SECONDS.toMicros( seconds )
;
Convert the remaining micros to nanos, because the Instant class we use next represents a count of whole seconds plus a count of nanoseconds (for the fractional second).
long nanos = TimeUnit.MICROSECONDS.toNanos( microsRemaining ) ;
Combine the whole seconds with the fractional second in nanos. The Instant class represents a moment in UTC as a count since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.
Instant instant = Instant.ofEpochSecond( seconds ).plusNanos( nanos ) ;
To generate a string in standard ISO 8601 format, simply call toString.
String output = instant.toString() ;
The Z on the end of the string means UTC (an offset-from-UTC of zero hours-minutes-seconds), and is pronounced Zulu.
You can produce strings in your own custom formats using the DateTimeFormatter class. Search Stack Overflow as this has been covered many many many times already.
Tip: Your desired format is so close to the ISO 8601 format, YYYY-MM-DDTHH:MM:SSZ, that I strongly suggest using the standard format rather than make up your own cousin of that.
If you wish to see this same moment through the lens of the wall-clock time used by people of a certain region (a time zone), apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Africa/Tunisia" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
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.
I am getting getTimestampMillis() from a SmsMessage sms and trying to convert that to MM/dd/yy hh:mm a.
I am using the code below, which works except it returns an hour ahead. Example it is 6-28-15 9:22 pm, the code returns 6-28-15 10:22 pm. I have read this is a java bug because London didnt observe GMT in 1970, or something similar. Is there a fix, or workaround that doesn't require me to subtract an hour in the summer and then change the code back after DST?
long time = currentMessage.getTimestampMillis();
Log.i(TAG, "time stamp in millis= "+time);
Time date = new Time(time);
DateFormat format = new SimpleDateFormat("MM/dd/yy hh:mm a");
String timestamp = format.format(date);
Log.i(TAG, "Human readable timestamp= "+timestamp);
tl;dr
Instant.ofEpochMilli( millisSinceEpoch )
GMT represents mean solar time, and is practically synonymous with UTC. Do not confuse this with the time zone Europe/London which has observed Daylight Saving Time (DST).
java.time
Never use java.sql.Time, DateFormat, or any of the legacy date-time classes bundled with the earliest versions of Java.
The modern solution uses java.time classes.
I assume your count of milliseconds was since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.
long millisSinceEpoch = currentMessage.getTimestampMillis();
Convert to a Instant object.
Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;
An Instant is always in UTC, by definition. So you will not have any surprises from Daylight Saving Time (DST).
Generate text in standard ISO 8601 format.
String output = instant.toString() ;
You did not specify your example value of epoch milliseconds. But we can work backwards to deduce it.
// Example it is 6-28-15 9:22
LocalDate ld = LocalDate.of( 2015 , Month.JUNE , 28 ) ;
LocalTime lt = LocalTime.of( 9 , 22 ) ;
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
Instant instant = odt.toInstant() ;
long epochMilli = instant.toEpochMilli() ;
1435483320000
See this code run live at IdeOne.com.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
UTC and GMT are two different things. UTC does not experience DST, whereas GMT does. Two steps:
1. Find out what time standard your host is actually using (java will be using this).
2. Probably just ignore that completely, and explicitly declare which timezone you want to use.
And if you find that playing with timezones is tedious, annoying, and confusing, consider using library joda-time. It's much more versatile and pleasant to use than built-in java stuff.
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.
This question already has answers here:
Epoch is not epoch if do a new Date(0L). Why?
(4 answers)
Closed 5 years ago.
The Java doc describe that the constructor Date(long date) constructs a Date object using the given milliseconds time value since January 1, 1970, 00:00:00 GMT
When I did new Date(0), the date is Jan 01 01:00:00 CET 1970
I don't know why it begin with 01h
It's show 1AM because you're an hour ahead of GMT. A date instance is simply a counter of the number of milliseconds since 00:00:00 1970 GMT. Since your an hour ahead, when the epoch occurred it was actually 1AM your time.
The Date instance simply formats its toString() method to use your system's timezone. If you want to print out a date using a different zone, use a DateFormat instance.
This is because you are showing the date in the European timezone (CET) the unix time (the milliseconds you are giving the Date object) use GMT.
tl;dr
Instant.now() // Current moment in UTC.
Details
The Answer by Nichols is correct but outdated.
Your own time zone was an hour ahead of UTC on that date, so midnight in UTC is 1 AM in your zone.
Nowadays you should be using java.time classes such as Instant instead of Date.
Avoid legacy classes
Avoid the troublesome old date-time classes now supplanted by the java.time classes.
Among the many problems of the legacy classes was the poor design choice to have the toString method dynamically apply the JVM’s current default time zone while generating the string representing the object’s value. A Date actually represents a moment in UTC. Avoid awkward class entirely. If necessary, convert between the legacy and modern classes via new methods added to the old classes.
Instant for UTC
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.
instant.toString(): 2018-02-11T21:07:02.315283Z
If you want the epoch reference moment used by the java.time classes, the first moment of 1970 in UTC, use the predefined constant: Instant.EPOCH.
Instant.EPOCH.toString(): 1970-01-01T00:00:00Z
OffsetDateTime
If you need more flexibility, such as generating strings in other formatting, convert the Instant object to a OffsetDateTime using the constant ZoneOffset.UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
ISO 8601
When exchanging date-time values as text, use the standard ISO 8601 formats. They were designed to be easy to parse by machine while also being easy to read by humans across various cultures.
The java.time classes use the standard ISO 8601 formats by default when generating/parsing strings. So no need to specify a formatting pattern.
Time zone, ZonedDateTime
If you want to see the same simultaneous moment through the lens of the wall-clock time used by the people of another region, apply a time zone (ZoneId) to get a ZonedDateTime object.
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 CET as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Europe/Paris" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-02-11T22:07:02.315283+01:00[Europe/Paris]
Let's look at the java.time epoch reference moment through the same time zone.
ZonedDateTime zdtEpochParis = Instant.EPOCH.atZone( z ) ;
zdtEpochParis.toString(): 1970-01-01T01:00+01:00[Europe/Paris]
Again, for another time zone.
ZonedDateTime zdtEpochMontreal = Instant.EPOCH.atZone( ZoneId.of( "America/Montreal" ) ) ;
zdtEpochMontreal.toString(): 1969-12-31T19:00-05:00[America/Montreal]
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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, 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.