Time in seconds is same even if you choose any TimeZone? - java

I am using below function to get time in seconds after I apply TimeZone "Europe/Warsaw".
I am getting date correctly, but as soon as I convert date in seconds, my output goes wrong. Server expects seconds in TimeZone "Europe/Warsaw". What's the best possible way to get out of this?
public static long getTimeInSeconds() {
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
//Will get in Warsaw time zone
String date = sdf.format(calendar.getTime());
Date date1 = sdf.parse(date);
//Convert time in seconds as required by server.
return (date1.getTime() / 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}

"seconds in TimeZone" doesn't make sense, because epoch seconds means "the number of seconds since epoch" (where epoch is Jan 1st 1970 at midnight in UTC), regardless of the timezone.
This value is the same everywhere in the world. But the same epoch seconds value can be converted to a local date and time, depending on the timezone.
Example: right now, the epoch second value is 1520352472. This same value (1520352472 seconds since epoch), is the same everywhere in the world. But this value can represent a different date and time in each timezone:
March 6th 2018, 16:07:52 in UTC
March 6th 2018, 13:07:52 in São Paulo (Brazil)
March 7th 2018, 01:07:52 in Tokyo
The thing is: no matter in what timezone I'm in, the epoch seconds value will be the same, so you don't need to consider any timezone at all.
The java.util.Date class doesn't have any notion of timezone as well, it just wraps a long value representing the number of milliseconds since epoch. So, if you hava a Date object, just use this value and divide by 1000:
long epochSeconds = new Date().getTime() / 1000;
Actually, if you want just the numeric value for the current date/time, you don't even need to create a Date to get it:
long epochSeconds = System.currentTimeMillis() / 1000;

tl;dr
To get a count of whole seconds since the epoch reference of 1970-01-01T00:00Z:
Instant.now().getEpochSecond()
Alternate route, with same result:
ZonedDateTime.now( ZoneId.of( "Europe/Warsaw" ) ).toInstant().getEpochSecond()
java.time
What's the best possible way to get out of this?
The best way is to use the modern java.time classes that years ago supplanted the terrible Date, Calendar, and SimpleDateFormat classes.
Apparently you want two things:
The current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
A count of whole seconds since the epoch reference of first moment of 1970 in UTC.
The first, getting current moment in a time zone. We use the ZoneId and ZonedDateTime classes.
ZoneId z = ZoneId.of( "Europe/Warsaw" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
See this code run live at IdeOne.com.
zdt.toString(): 2020-02-09T21:14:56.417009+01:00[Europe/Warsaw]
To get the count of seconds since 1970-01-01T00:00Z, extract an Instant. This class represents a moment as seen in UTC, with an offset of zero hours-minutes-seconds.
Instant instant = zdt.toInstant() ;
See this code run live at IdeOne.com.
instant.toString(): 2020-02-09T20:14:56.417009Z
Both variables zdt and instant represent the very same moment, the same point on the timeline. Only the wall-clock time is different.
Interrogate for the count of whole seconds from the epoch reference.
long secondsSinceEpoch = instant.getEpochSecond() ; // Beware of data-loss, as fractional second is ignored.
See this code run live at IdeOne.com.
secondsSinceEpoch: 1581279296
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 need to set the time-zone after getting the time from the calendar
public static long getTimeInSeconds() {
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Will get in Warsaw time zone
String date = sdf.format(calendar.getTime());
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
Date date1 = sdf.parse(date);
//Convert time in seconds as required by server.
return (date1.getTime() / 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}

Related

Confusions about Java's Date class and getTime() function

I am new to Java's Date class. When I try to use its getTime() function for calculating time difference, issues come out. For example, below is the code.
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
task = opt.get();
task.setEndDate(dateFormat.format(date));
Date startDate = null;
try {
startDate = dateFormat.parse(task.getStartDate());
} catch (ParseException e) {
System.out.println("date parsing error...");
startDate = date;
}
System.out.printf("Start date is: %s", task.getStartDate());
System.out.printf("Start date is: %d", startDate.getTime());
System.out.printf("End date is: %s", task.getEndDate());
System.out.printf("End date is: %d", date.getTime());
long diff = date.getTime() - startDate.getTime() - 43200000;
System.out.printf("Time difference is: %d", diff);
int secNum = (int)(diff / 1000);
String timeCost = String.valueOf(secNum);
System.out.println("Time cost(sec) is:");
System.out.println(timeCost);
task.setTimeCost(timeCost);
The outputs are:
Start date is: 2020-04-15 01:46:17
Start date is: 1586929577000
End date is: 2020-04-15 01:46:35
End date is: 1586972795461
Time difference is: 18461
Time cost(sec) is:18
As you might notice, there is 12 hours(43200000 ms) offset between the calculated difference and the real difference through "date.getTime() - startDate.getTime()".
I don't know what's going on.
Does anyone have an idea and correct me ?
It seems you are storing the date/time as a string in your task object, and converting between Date and String using the format "yyyy-MM-dd hh:mm:ss". I believe lower-case h means you are using a 12-hour clock, but you do not include an AM/PM indicator in your format string.
I'm guessing you ran the code at 1:46 PM to produce the sample output.
You have "2020-04-15 01:46:17" stored as your start date. When you convert that back to a date, the formatter doesn't know whether it is an AM time or PM time. I guess that it defaults to AM.
The Date object, however, knows that it was initialized with a PM time. Therefore, when you subtract the two, you get over 12 hours difference, because it is subtracting 1:46:17 AM from 1:46:35 PM.
A simple recommendation would be to add an AM/PM indicator to your date format, or use a 24-hour clock (upper-case H in the format string).
An even better recommendation would be to store dates as dates, not as strings! Convert them to strings when you want to display them.
You are using hh which is a 12-hour hour format, hence 20:00 becomes 08:00. You should use HH which is a 24-hour format. The below illustrates the difference.
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Date date = new Date(1586973600000L);
System.out.println(date);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String fd1 = df.format(date);
System.out.println(fd1);
System.out.println(df.parse(fd1));
df.applyPattern("yyyy-MM-dd HH:mm:ss");
String fd2 = df.format(date);
System.out.println(fd2);
System.out.println(df.parse(fd2));
Also, java.util.Date is old, buggy and generally avoided for some time now. You might want to switch to java.time instead.
java.time
I am new to Java's Date class.
Stop! Backup, rewind.
Both java.util.Date and java.sql.Date classes are terrible, deeply flawed, and quite frustrating. Never use these classes.
These classes were shipped in the earliest versions of Java. Supplanted years ago by the modern java.time classes defined in JSR 310.
Date date = new Date();
To capture the current moment in UTC, use Instant.now. Uses a resolution finer than the milliseconds used in the java.util.Date class it replaced.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
task.setEndDate(dateFormat.format(date));
Your Task class should hold a java.time object rather than a mere string.
class Task {
Instant start , stop ;
…
}
Use smart objects rather than dumb strings throughout your Java codebase. Doing so ensures valid values, provides type-safety, and makes your code more self-documenting.
If your Task is like booking appointments in the future, where you want a certain time-of-day regardless of changes to the offset used by your time zone, then use LocalDateTime. This type represents only a date and time-of-day but lacks any concept of time zone or offset.
LocalDate ld = LocalDate.of( 2020 , Month.APRIL , 15 ) ;
Localtime lt = LocalTime.of( 15 , 30 ) ;
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
When generating a calendar where you need a specific point on the timeline, then apply the relevant time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
The issue at stake here is the fact that politicians around the world have shown a predilection for changing the offset used by the time zone(s) of their jurisdiction. The politicians do so with surprising frequency. And they have done so with little or no forewarning.
When exchanging date-time values with other systems textually, then use ISO 8601 formats. These formats are used by default in java.time when parsing/generating text. And for presentation to users, produce automatically localized strings using DateTimeFormatter.
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
This format is incorrect if you are trying to record moments, specific points on the timeline. You must include an indication of time zone and/or offset-from-UTC to track a moment.
For moments, use the ISO 8601 formats mentioned above. Used by default, so no need to specify a formatting pattern.
String input = "2020-01-23T01:23:45.123456789Z" ;
Instant instant = Instant.parse( input ) ;
Adjust from UTC into the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate localized text.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;
String output = zdt.format( f ) ;
See this code run live at IdeOne.com.
zdt.toString(): 2020-01-22T20:23:45.123456789-05:00[America/Montreal]
output: mercredi 22 janvier 2020 à 20 h 23 min 45 s heure normale de l’Est
long diff = date.getTime() - startDate.getTime() - 43200000;
No need to do the math yourself. We have a class for that: Duration.
Duration d = Duration.between( start , stop ) ;
If you want a count of whole seconds across the entire span of time, call Duration::toSeconds.
long seconds = d.toSeconds() ; // Entire duration in terms of whole seconds.
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 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.

Convert UTC time to local time zone

I have to convert UTC time into user local time zone. Currently, I have the two parameters one is time in long format and another is time zone name in string format like "(UTC-05:00) Eastern Time (US and Canada), (UTC-06:00) Central Time (US and Canada)" etc.
So now using these two parameters I have to get date time in string format. I am facing the issue while I am trying to convert the date into a string because the SimpleDateFormat.format(...) will convert the date using its default time zone.
Below are the code portion
public static void main(String[] args)
{
long time = 1490112300000L;
System.out.println("UTC Time "+ convertLongToStringUTC(time));
String EST = "(UTC-05:00) Eastern Time (US and Canada)";
TimeZone timeZone1 = TimeZone.getTimeZone(EST);
System.out.println("EST "+ convertTimeZone(time, timeZone1));
String CST = "(UTC-06:00) Central Time (US and Canada)";
TimeZone timeZone2 = TimeZone.getTimeZone(CST);
System.out.println("CST "+ convertTimeZone(time, timeZone2));
String IST = "IST";
TimeZone timeZone = TimeZone.getTimeZone(IST);
System.out.println("IST "+ convertTimeZone(time, timeZone));
}
public String convertTimeZone(long time, TimeZone timeZone)
{
Date date = new Date(time);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(timeZone);
return format.format(date);
}
public String convertLongToStringUTC(long time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date(time));
return utcTime;
}
Also let me know if we can achieve this using offset ?
Use this constructor
SimpleDateFormat(String pattern, Locale locale)
Constructs a SimpleDateFormat using the given pattern and the default
date format symbols for the given locale. Note: This constructor may
not support all locales. For full coverage, use the factory methods in
the DateFormat class.
Java Doc
tl;dr
Instant.ofEpochMilli( 1_490_112_300_000L )
.atOffset( ZoneOffset.of( "-05:00" ) )
Instant.ofEpochMilli( 1_490_112_300_000L )
.atZone( ZoneId.of( "America/New_York" ) )
Details
The Answer by Dennis is close. I will provide further information.
Your Question is not exactly clear about the inputs. I will assume your long integer number represents a moment in UTC.
An offset-from-UTC is an number of hours and minutes and seconds before or after UTC. In java.time, we represent that with a ZoneOffset.
While ZoneId technically works (as seen in code by Dennis), that is misleading as a zone is much more than an offset. A zone is a region’s history of various offsets that were in effect at different periods of history. A zone also includes any planned future changes such as DST cutovers coming in the next months.
ZoneOffset offset = ZoneOffset.of( 5 , 30 ); // Five-and-a-half hours ahead of UTC.
ZoneOffset offset = ZoneOffset.of( "+05:30" );
Tip: Always include the padding zero on the hours. While not always required in various protocols such as ISO 8601, I have seen software systems burp when encountering single-digit hours like +5:00.
If you know the intended time zone for certain, use it. A zone is always better than a mere offset as it brings all that historical information of other offsets for the past, present, and future.
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 as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" );
I am guessing your number is a number of milliseconds since the epoch of 1970-01-01T00:00:00Z.
Instant instant = Instant.ofEpochMilli( 1_490_112_300_000L );
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).
You can adjust into a time zone.
ZonedDateTime zdt = instant.atZone( z );
These issues have been covered many times in Stack Overflow. Hence the down-votes you are collecting (I am guessing). Please search Stack Overflow thoroughly before posting.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Using Java 8 you can do
OffsetDateTime dt = Instant.ofEpochMilli(System.currentTimeMillis())
.atOffset( ZoneOffset.of("-05:00"));
//In zone id you put the string of the offset you want

Calendar Date Java, skip one hour on 2014-02-16

I found this funny behavior while using Date and Calendar class to handle Exponential distributions for simulating arrival time at a store (academic work). The code is quite simple and is below displayed. Well suppose that "this.currentDate" is "Feb 15 08:00:00 BRST 2014".
If i shift forward the time 24h (parameter iSeconds=86.400), what is supposed to return ? The expected string would be "2014-02-16 08:00:00" but instead the time is shortened in 1h and the result is "2014-02-16 07:00:00", I wonder if someone could explain why my one hour was "stolen". No big deal, but since my next arrival time depends of the earlier one, it makes a mess over my time baseline shifting all of them one hour as well.
I thought could be some TZ issue, but heck, i just moved 24h in the middle of February.
public String shiftTimeStamp( int iSeconds)
{
Calendar cal = Calendar.getInstance();
cal.setTime(this.currentDate);
cal.add(Calendar.SECOND, iSeconds);
this.currentDate = cal.getTime();
String sTS = new SimpleDateFormat(SCSimLabels.DATE_TS_FORMAT).format(this.currentDate);
return sTS;
}
Note: Daylight Saving Time issue :) BRT <--> BRST tz.
my workaround: I just want a beacon to guide the time jumps caused by inter arrival times and I´m not interested on such calendar specificities, so when I need to move to the first work hour of the next day I just force the time to be 08:00:00 after 1 day shift. It works like a charm :)
Calendar cal = Calendar.getInstance();
cal.setTime(this.currentDate);
cal.add(Calendar.DATE, 1);
String sDate = (new SimpleDateFormat("yyyy-MM-dd 08:00:00")).format(cal.getTime());
Date newDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sDate);
this.currentDate = newDate;
Change the format call to this:
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(this.currentDate);
To see what timezone the format call is using. I bet the call to .add() is modifying the Calendar object's timezone since it crosses the standard time / daylight time border.
If this is the case, you could try adding a Calendar.DAY,1 or simply .setTimeZone(...) of the Calendar obj. back to the original timezone after the .add call.
Avoid legacy date-time classes
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Using java.time
If you want to work with generic 24-hour days without any time zone or offset-from-UTC, use the LocalDateTime class. If you always want to start at 8 AM, specify a LocalTime.
LocalDate ld = LocalDate.of( 2014 , Month.FEBRUARY , 15 ) ;
LocalTime lt = LocalTime.of( 8 , 0 ) ; // Specify hour in 24-hour clock, 0-23.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
Represent your 24 hour span as a Duration.
Duration d = Duration.ofHours( 24 );
LocalDateTime ldtLater = ldt.plus( d );
If you want to work with specific moments on the timeline as seen through the lens of a region’s particular wall-clock time, then specify a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Sao_Paulo" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
ZonedDateTime zdtLater = zdt.plus( d );
Note that adding 24 hours to a ZonedDateTime is not the same thing as adding a day. As you have learned the hard way, anomalies such as Daylight Saving Time (DST) means a day may be 23, 24, or 25 hours long, or even other lengths. So if you want to add a day and let java.time apply its logic to arrive at an appropriate time-of-day while taking into consideration anomalies such as DST, add days rather than hours.
ZonedDateTime zdtLater = zdt.plusDays( 1 );
Or add a Period of one whole day rather than a Duration of 24 hours.
Period p = Period.ofDays( 1 );
ZonedDateTime zdtLater = zdt.plus( p );
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, 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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to make date.getTime() returns UTC time?

I have a Date object which represents a UTC time. When I use the method getTime() to get the long value of this object, the value returned corresponds to our local time (central US). What is the correct way to get the value back which corresponds to the original UTC time?
Thanks
tl;dr
Instant.now()
…and…
Instant.ofEpochMilli( n )
…and…
instant.toEpochMilli()
Date is always in UTC
When I use the method getTime() to get the long value of this object, the value returned corresponds to our local time (central US).
No, the value returned from Date::getTime() always corresponds to UTC (virtually the same thing as GMT in this context). To quote the class doc:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
So your Question is nonsensical in that a Date is already in UTC. No need to “get the value back which corresponds to the original UTC time”,
You may be confusing the behavior of getTime with that of the toString method. The toString method annoyingly and confusingly applies the current default time zone in the process of generating the String. So the string output appears with a time zone while in fact there is no time zone to be set or gotten from the Date itself. (There actually is a zone deep within the Date but that is irrelevant to this discussion here. This class is a confusing mess!)
java.time
The modern way to do this is using 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).
Get the current moment.
Instant instant = Instant.now();
You can convert a Date to its modern replacement by calling one of the new conversion methods added to the old date-time classes. Just call toInstant, quite easy.
Instant instant = myJavaUtilDate.toInstant();
I do not recommend at all using a count-from-epoch number as a way of tracking time. Stick with the java.time objects instead. When outside Java, serialize to text use the ISO 8601 formats.
But if you must, you can extract a count of milliseconds since epoch of 1970-01-01T00:00:00Z. Note that this may involve data loss! An Instant has a finer resolution of nanoseconds. So going to milliseconds may lop off a fraction of the fraction of a second.
long millisecondsSinceEpoch = instant.toEpochMilli(); // Caution: Possible data-loss in going from nanoseconds to milliseconds.
Going the other direction, from a count to an Instant.
Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch ) ;
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….
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.
The DateFormat class has a method for setting your preferred time zone, and there's a time zone class that has a setting for UTC time.
So, for example,
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
Date yourUtcDate = sdf.parse(yourOriginalDate);
java.util.Date has no concept of timezone. It simply holds time relative to epoch, which is Jan 1 1970 00:00:00 UTC. Date is a model, separate from the view. When you display the date, the concept of timezone then is applied. Date's toString() displays a human readable date in the default timezone. You can either use a DateFormat to display a Date in a different timezone (such as UTC), or change the JVM's default timezone.
getTime() returns "the number of milliseconds since January 1, 1970, 00:00:00 GMT", nothing more, nothing less (obviously, you have to create it correctly). You can format it however you want, starting with e.g. the GregorianCalendar(TimeZone) constructor.
Most of the Date class functions are deprecated as they are now shifted in Calendar class.
Here is code to get UTC time from Calendar.
Date date = new Date(timeStamp);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);
Here is the sample code to get the year, month, etc.
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));
Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them Please note that the month are 0 based. January is 0th month.
LocalDateTime now = LocalDateTime.now(Clock.systemUTC());
Instant instant = now.atZone(ZoneId.systemDefault()).toInstant();
Date formattedDate = Date.from(instant);
return formattedDate;

Date.getTime() not including time?

Can't understand why the following takes place:
String date = "06-04-2007 07:05";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date myDate = fmt.parse(date);
System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007
long timestamp = myDate.getTime();
System.out.println(timestamp); //1180955100000 -- where are the milliseconds?
// on the other hand...
myDate = new Date();
System.out.println(myDate); //Tue Sep 16 13:02:44 EDT 2008
timestamp = myDate.getTime();
System.out.println(timestamp); //1221584564703 -- why, oh, why?
What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?
String date = "06-04-2007 07:05:00.999";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S");
Date myDate = fmt.parse(date);
System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println(timestamp);
Because simple date format you specified discards the milliseconds. So the resulting Date object does not have that info. So when you print it out, its all 0s.
On the other hand, the Date object does retain the milliseconds when you assign it a value with milliseconds (in this case, using new Date()). So when you print them out, it contains the millisecs too.
Instead of using the Sun JDK Time/Date libraries (which leave much to be desired) I recommend taking a look at http://joda-time.sourceforge.net.
This is a very mature and active sourceforge project and has a very elegant API.
tl;dr
The accepted Answer by Vinko Vrsalovic is correct. Your input is whole minutes, so the milliseconds for fractional second should indeed be zero.
Use java.time.
LocalDateTime.parse
(
"06-04-2007 07:05" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm" )
)
.atZone
(
ZoneId.of( "Africa/Casablanca" )
)
.toInstant()
.getEpochMilli()
java.time
The modern approach uses the java.time classes defined in JSR 310 that years ago supplanted the terrible classes you are using.
Define a formatting pattern to match your input. FYI: Learn to use standard ISO 8601 formats for exchanging date-time values as text.
String input = "06-04-2007 07:05" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm" ) ;
Parse your input as a LocalDateTime, as it lacks an indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
This represents a date and a time-of-day, but lacks the context of a time zone or offset. So we do not know if you meant 7 AM in Tokyo Japan, 7 AM in Toulouse France, or 7 AM in Toledo Ohio US. This issue of time zone is crucial, because your desired count of milliseconds is a count since the first moment of 1970 as seen in UTC (an offset of zero hours-minutes-seconds), 1970-01-01T00:00Z.
So we must place your input value, the LocalDateTime object, in the context of a time zone or offset.
If your input was intended to represent a date and time in UTC, use OffsetDateTime with ZoneOffset.UTC.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ; // Do this if your date and time represent a moment as seen in UTC.
If your input was intended to represent a date and time as seen through the wall-clock time used by the people of a particular region, use ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Next we want to interrogate for the count of milliseconds since the epoch of first moment of 1970 in UTC. With either a OffsetDateTime or ZonedDateTime object in hand, extract a Instant by calling toInstant.
Instant instant = odt.toInstant() ;
…or…
Instant instant = zdt.toInstant() ;
Now get count of milliseconds.
long millisecondsSinceEpoch = instant.toEpochMilli() ;
By the way, I suggest you not track time by a count of milliseconds. Use ISO 8601 formatted text instead: easy to parse by machine, easy to read by humans across cultures. A count of milliseconds is neither.
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 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….
When you parse a date it only uses the information you provide.
In this case it only knows MM-dd-yyyy HH:mm.
Creating a new date object returns the current system date/time (number of milliseconds since the epoch).
toString() of a Date object does not show you the milliseconds... But they are there
So new Date() is an object with milisecond resolution, as can be seen by:
System.out.printf( "ms = %d\n", myDate.getTime() % 1000 ) ;
However, when you construct your date with SimpleDateFormat, no milliseconds are passed to it
Am I missing the question here?
[edit] Hahaha...way too slow ;)
Date.getTime returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by the Date object. So "06-04-2007 07:05" - "01-01-1970 00:00" is equal to 1180955340000 milliseconds. Since the only concern of your question is about the time portion of the date, a rough way of thinking of this calculation is the number of milliseconds between 07:05 and 00:00 which is 25500000. This is evenly divisible by 1000 since neither time has any milliseconds.
In the second date it uses the current time when that line of code is executed. That will use whatever the current milliseconds past the current second are in the calculation. Therefore, Date.getTime will more than likely return a number that is not evenly divisible by 1000.
The getTime() method of Date returns the number of milliseconds since January 1, 1970 (this date is called the "epoch" because all computer dates are based off of this date). It should not be used to display a human-readable version of your Date.
Use the SimpleDateFormat.format() method instead. Here is a revised version of part of your code that I think may solve your problem:
String date = "06-04-2007 07:05:23:123";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss:S");
Date myDate = fmt.parse(date);
System.out.println(myDate); //Mon Jun 04 07:05:23 EDT 2007
String formattedDate = fmt.format(myDate);
System.out.println(formattedDate); //06-04-2007 07:05:23:123
import java.util.*;
public class Time {
public static void main(String[] args) {
Long l = 0L;
Calendar c = Calendar.getInstance();
//milli sec part of current time
l = c.getTimeInMillis() % 1000;
//current time without millisec
StringBuffer sb = new StringBuffer(c.getTime().toString());
//millisec in string
String s = ":" + l.toString();
//insert at right place
sb.insert(19, s);
//ENJOY
System.out.println(sb);
}
}

Categories