Convert LocalDate to LocalDateTime or java.sql.Timestamp - java

I am using JodaTime 1.6.2.
I have a LocalDate that I need to convert to either a (Joda) LocalDateTime, or a java.sqlTimestamp for ormapping.
The reason for this is I have figured out how to convert between a LocalDateTime and a java.sql.Timestamp:
LocalDateTime ldt = new LocalDateTime();
DateTimeFormatter dtf = DateTimeFormatter.forPattern("yyyy-MM-dd HH:mm:ss");
Timestamp ts = Timestamp.valueOf(ldt.toString(dtf));
So, if I can just convert between LocalDate and LocalDateTime, then I can make the continued conversion to java.sql.Timestamp. Thanks for any nudges in the right direction!

JodaTime
To convert JodaTime's org.joda.time.LocalDate to java.sql.Timestamp, just do
Timestamp timestamp = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());
To convert JodaTime's org.joda.time.LocalDateTime to java.sql.Timestamp, just do
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
JavaTime
To convert Java8's java.time.LocalDate to java.sql.Timestamp, just do
Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay());
To convert Java8's java.time.LocalDateTime to java.sql.Timestamp, just do
Timestamp timestamp = Timestamp.valueOf(localDateTime);

The best way use Java 8 time API:
LocalDateTime ldt = timeStamp.toLocalDateTime();
Timestamp ts = Timestamp.valueOf(ldt);
For use with JPA put in with your model (https://weblogs.java.net/blog/montanajava/archive/2014/06/17/using-java-8-datetime-classes-jpa):
#Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(LocalDateTime ldt) {
return Timestamp.valueOf(ldt);
}
#Override
public LocalDateTime convertToEntityAttribute(Timestamp ts) {
return ts.toLocalDateTime();
}
}
So now it is relative timezone independent time.
Additionally it is easy do:
LocalDate ld = ldt.toLocalDate();
LocalTime lt = ldt.toLocalTime();
Formatting:
DateTimeFormatter DATE_TME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
String str = ldt.format(DATE_TME_FORMATTER);
ldt = LocalDateTime.parse(str, DATE_TME_FORMATTER);
UPDATE: postgres 9.4.1208, HSQLDB 2.4.0 etc understand Java 8 Time API without any conversations!

tl;dr
The Joda-Time project is in maintenance-mode, now supplanted by java.time classes.
Just use java.time.Instant class.
No need for:
LocalDateTime
java.sql.Timestamp
Strings
Capture current moment in UTC.
Instant.now()
To store that moment in database:
myPreparedStatement.setObject( … , Instant.now() ) // Writes an `Instant` to database.
To retrieve that moment from datbase:
myResultSet.getObject( … , Instant.class ) // Instantiates a `Instant`
To adjust the wall-clock time to that of a particular time zone.
instant.atZone( z ) // Instantiates a `ZonedDateTime`
LocalDateTime is the wrong class
Other Answers are correct, but they fail to point out that LocalDateTime is the wrong class for your purpose.
In both java.time and Joda-Time, a LocalDateTime purposely lacks any concept of time zone or offset-from-UTC. As such, it does not represent a moment, and is not a point on the timeline. A LocalDateTime represents a rough idea about potential moments along a range of about 26-27 hours.
Use a LocalDateTime for either when the zone/offset is unknown (not a good situation), or when the zone-offset is indeterminate. For example, “Christmas starts at first moment of December 25, 2018” would be represented as a LocalDateTime.
Use a ZonedDateTime to represent a moment in a particular time zone. For example, Christmas starting in any particular zone such as Pacific/Auckland or America/Montreal would be represented with a ZonedDateTime object.
For a moment always in UTC, use Instant.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Apply a time zone. Same moment, same point on the timeline, but viewed with a different wall-clock time.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
So, if I can just convert between LocalDate and LocalDateTime,
No, wrong strategy. If you have a date-only value, and you want a date-time value, you must specify a time-of-day. That time-of-day may not be valid on that date for a particular zone – in which case ZonedDateTime class automatically adjusts the time-of-day as needed.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
LocalTime lt = LocalTime.of( 14 , 0 ) ; // 14:00 = 2 PM.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
If you want the first moment of the day as your time-of-day, let java.time determine that moment. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00.
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
java.sql.Timestamp is the wrong class
The java.sql.Timestamp is part of the troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. That class was used to represent a moment in UTC with a resolution of nanoseconds. That purpose is now served with java.time.Instant.
JDBC 4.2 with getObject/setObject
As of JDBC 4.2 and later, your JDBC driver can directly exchange java.time objects with the database by calling:
PreparedStatement::setObject
ResultSet::getObject
For example:
myPreparedStatement.setObject( … , instant ) ;
… and …
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Convert legacy ⬌ modern
If you must interface with old code not yet updated to java.time, convert back and forth using new methods added to the old classes.
Instant instant = myJavaSqlTimestamp.toInstant() ; // Going from legacy class to modern class.
…and…
java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( instant ) ; // Going from modern class to legacy class.
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.

function call asStartOfDay() on java.time.LocalDate object returns a java.time.LocalDateTime object

Depending on your timezone, you may lose a few minutes (1650-01-01 00:00:00 becomes 1649-12-31 23:52:58)
Use the following code to avoid that
new Timestamp(localDateTime.getYear() - 1900, localDateTime.getMonthOfYear() - 1, localDateTime.getDayOfMonth(), localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(), localDateTime.getSecondOfMinute(), fractional);

Since Joda is getting faded, someone might want to convert LocaltDate to LocalDateTime in Java 8. In Java 8 LocalDateTime it will give a way to create a LocalDateTime instance using a LocalDate and LocalTime. Check here.
public static LocalDateTime of(LocalDate date,
LocalTime time)
Sample would be,
// just to create a sample LocalDate
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
// convert ld into a LocalDateTime
// We need to specify the LocalTime component here as well, it can be any accepted value
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00
Just for reference, For getting the epoch seconds below can be used,
ZoneId zoneId = ZoneId.systemDefault();
long epoch = ldt.atZone(zoneId).toEpochSecond();
// If you only care about UTC
long epochUTC = ldt.toEpochSecond(ZoneOffset.UTC);

Java8 +
import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)

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.

Comparing time in java between epoch milliseconds and LocalDateTime

I have a timestamp in epoch milliseconds and I want to check if it is between two LocalDateTime stamps. What's the best way to do this in java?
One way to do it is to convert the milliseconds to LocalDateTime
LocalDateTime date = Instant.ofEpochMilli(milliseconds)
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
LocalDateTime start = LocalDateTime.now().minusMinutes(1);
LocalDateTime end = LocalDateTime.now().plusMinutes(1);
if (date.isAfter(start) && date.isBefore(end)) {
// date is between start and end
}
tl;dr
You cannot compare a LocalDateTime to a moment until assigning a time zone (or offset-from-UTC).
org.threeten.extra.Interval // Represents a span-of-time attached to the timeline, as a pair of `Instant` objects, a pair of moments in UTC.
.of (
myLocalDateTimeStart
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Determine a moment by assigning an time zone to a `LocalDateTime` to produce a `ZonedDateTime`, from which we extract an `Instant` to adjust into UTC.
.toInstant() ,
myLocalDateTimeStop
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Returns a `ZonedDateTime` object.
.toInstant() // From the `ZonedDateTime`, extract a `Instant` object.
) // Returns `Interval` object.
.contains(
Instant.ofEpochMilli( 1_532_463_173_752L ) // Parse a count of milliseconds since 1970-01-01T00:00:00Z as a moment in UTC, a `Instant` object.
) // Returns a boolean.
Details
Comparing time in java between epoch milliseconds and LocalDateTime
You cannot. That comparison is illogical.
A LocalDateTime does not represent a moment, is not a point on the timeline. A LocalDateTime represents potential moments along a range of about 26-27 hours, the range of time zones around the world.
As such it has no real meaning until you place it in the context of a time zone. If that particular date and time were invalid in that zone, such as during a Daylight Saving Time (DST) cut-over, or during some other such anomaly, the ZonedDateTime class adjusts.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = myLocalDateTime.atZone( z ) ;
For comparisons, we will adjust into UTC by extracting an Instant object from your start and stop ZonedDateTime objects.
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
Now parse your count of milliseconds since the epoch reference of first moment of 1970 as a Instant. Instant has an even finer resolution, nanoseconds.
Instant instant = Instant.ofEpochMilli( 1_532_463_173_752L ) ;
Compare to see if your epoch-milliseconds represent a moment in between our stop and start Instant objects. Usually in date-time work, the Half-Open approach is best, where the beginning is inclusive while the ending is exclusive.
Tip: A shorter way of saying “is equal to or is after” is to say “is not before”.
boolean inRange = ( ! instant.isBefore( start ) ) && instant.isBefore( stop ) ;
To make this work easier, add the ThreeTen-Extra library to your project. Use the Interval class.
Interval interval = Interval.of( start , stop ) ;
boolean inRange = interval.contains( instant ) ; // Uses Half-Open approach to comparisons.
Tip: If you had intended to be tracking moments, you should not have been using LocalDateTime class at all. Instead, use the Instant, OffsetDateTime, and ZonedDateTime classes.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
When comparing an Instant (time-since-Epoch) with a LocalDateTime, you always need to consider the timezone of the local times. Here's an example:
Instant now = Instant.now();
LocalDateTime start = LocalDateTime.of(2018, 7, 24, 0, 0);
LocalDateTime end = LocalDateTime.of(2018, 7, 24, 23, 59);
final ZoneId myLocalZone = ZoneId.of("Europe/Paris");
if (now.isAfter(start.atZone(myLocalZone).toInstant())
&& now.isBefore(end.atZone(myLocalZone).toInstant())) {
// the instant is between the local date-times
}

Comparing current time with a time of data enty in database

I have a database in which I have users with their info etc. One field is named "maeindat" and there is stored the date of the entry (creation) of that entitiy ( user )
Now I want to compare if current time is "smaller" than input date and if it is set current date into the field, but if date of entry is bigger than current date set date of entry into the field
current date < date of entry --> set current date into the field
current date > date of entry --> set date of entry in field
Bellow is the code I'm trying out...
String maeindat = rs.getString("MAEINDAT");
LocalDateTime currTime = LocalDateTime.now();
if(currTime.isBefore(maeindat)) {
currTime = maeindat;
}
else if(currTime.isAfter(maeindat)) {
maeindat = maeindat;
}
UPDATE:
String maeindat = rs.getString("MAEINDAT");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMDDHH24MI");
LocalDateTime maeindatDate = LocalDateTime.parse(maeindat, formatter);
LocalDateTime currTime = LocalDateTime.now();
if(currTime.isBefore(maeindatDate)) {
currTime = maeindatDate;
}
else if (currTime.isAfter(maeindatDate)) {
maeindatDate = maeindatDate;
}
tl;dr
Comparing a LocalDateTime with current moment makes no sense logically.
myResultSet.getObject(
… ,
Instant.class // Retrieve from database column of type similar to SQL-standard `TIMESTAMP WITH TIME ZONE`.
).isBefore( Instant.now() ) // Or `isAfter` or `equals` or combine with `!` (meaning NOT before/after).
Apples & Oranges
You cannot compare strings to date-time objects. Parse your strings into date-time objects, and then you may compare.
LocalDateTime
The LocalDateTime class lacks any concept of time zone or offset-from-UTC. Use this class only if using a column in your database of a type similar to SQL-standard TIMESTAMP WITHOUT TIME ZONE.
This type is not intended to represent actual moments, specific points on the timeline. Instead this type is only a rough idea of potential moments spread over a range of about 26-27 hours.
If we say "Santa delivers the toys just after midnight on December 25th", do we mean just after midnight in Auckland, New Zealand or do we mean midnight in Kolkata India which occurs hours later? Or Paris France even more hours later? "Midnight" has no real meaning until you specify Auckland, Kolkata, or Paris.
Comparing a LocalDateTime to the current moment makes no sense! The LocalDateTime has no real meaning without the context of a time zone or offset. If you know for certain of an appropriate time zone for that value, apply a ZoneId to get a ZonedDateTime. At that point, you have an actual moment, a point on the timeline.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = myLocalDateTime.atZone( z ) ; // Converting vague idea about potential moments into an actual moment, a specific point on the timeline.
Instant
If you intend to represent actual moments, use SQL-standard type TIMESTAMP WITH TIME ZONE and Java type Instant (UTC) or possibly ZonedDateTime.
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 = myResultSet.getObject( … , Instant.class ) ;
Capture the current moment in UTC.
Instant instantNow = Instant.now() ; // Current moment in UTC.
Compare using isBefore, isAfter, equals.
boolean targetPassed = instant.isAfter( instantNow ) ;
Smart objects, not dumb strings.
With a JDBC driver complying with JDBC 4.2 and later, you may directly exchange java.time objects with your database. No need for converting to/from strings.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ; // For database column of type like `TIMESTAMP WITHOUT TIME ZONE`.
Or…
Instant instant = myResultSet.getObject( … , Instant.class ) ; // For database column of type like `TIMESTAMP WITH TIME ZONE`.
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
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.

Is there any way to convert ZoneId to ZoneOffset in Java 8?

I have an epoch second and a zoneId (see method1 below).
It can be convert to LocalDateTime with system default zoneId, but I don't find the way to convert epoch second to LocalDateTime (see method2 below), because there is no ZoneOffset.systemDefault. I think it's obscure.
import java.time.{Instant, LocalDateTime, ZoneId, ZoneOffset}
val epochSecond = System.currentTimeMillis() / 1000
// method1
LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), ZoneId.systemDefault())
// method2
LocalDateTime.ofEpochSecond(epochSecond, 0, ZoneOffset.MAX)
NOTE
The source code presented above is Scala.
Here is how you can get ZoneOffset from ZoneId:
Instant instant = Instant.now(); //can be LocalDateTime
ZoneId systemZone = ZoneId.systemDefault(); // my timezone
ZoneOffset currentOffsetForMyZone = systemZone.getRules().getOffset(instant);
NB: ZoneId can have different offset depending on point in time and the history of the particular place. So choosing different Instants would result in different offsets.
NB2: ZoneId.of() can return a ZoneOffset instead of ZoneId if UTC+3/GMT+2/etc is passed as opposed to a time zone like Africa/Cairo. So if UTC/GMT offsets are passed then historical/geographical/daylight-saving information of the Instant won't be taken into account - you'll simply work with the specified offset.
tl;dr
ZonedDateTime.now(
ZoneId.of( "America/Montreal" )
)
…of current default time zone…
ZonedDateTime.now(
ZoneId.systemDefault()
)
Details
The Answer by Stanislav Bshkyrtsev correctly and directly answers your Question.
But, there are larger issues involved, as suggested in the Answer by Jon Skeet.
LocalDateTime
I don't find the way to convert epoch second to LocalDateTime
LocalDateTime purposely has no concept of time zone or offset-from-UTC. Not likely what you want. The Local… means any locality, not any one particular locality. This class does not represent a moment, only potential moments along a range of about 26-27 hours (the range of time zones around the globe).
Instant
No need to start with epoch seconds if you are trying to get current time. Get the current Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
Inside of that Instant is a count of nanoseconds-from-epoch. But we do not really care.
See also, What's the difference between Instant and LocalDateTime?
ZonedDateTime
If you want to see that moment through the lens of a particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Europe/Paris" );
ZonedDateTime zdt = instant.atZone( z );
As a shortcut, you can do directly to the ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.now( z );
A ZonedDateTime has an Instant within it. Call zdt.toInstant() to get the same moment in time as a basic value in UTC. Same number of nanoseconds-since-epoch either way, as a ZonedDateTime or as a Instant.
Seconds-since-epoch given
If you are given a count of seconds-since-epoch, and the epoch is the first moment of 1970 in UTC (1970-01-01T00:00:00Z), then feed that number to Instant.
long secondsSinceEpoch = 1_484_063_246L ;
Instant instant = Instant.ofEpochSecond( secondsSinceEpoch ) ;
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.
There is no one-to-one mapping. A ZoneId defines a geographic extent in which a set of different ZoneOffsets is used over time. If the timezone uses daylight saving time, its ZoneOffset will be different between summer and winter.
Furthermore, the daylight saving time rules may have changed over time, so the ZoneOffset could be different for e.g. 13/10/2015 compared to 13/10/1980.
So you can only find the ZoneOffset for a ZoneId on a particular Instant.
See also https://en.wikipedia.org/wiki/Tz_database
As the documentation says, "This is primarily intended for low-level conversions rather than general application usage."
Going via Instant makes perfect sense to me - your epoch second is effectively a different representation of an Instant, so convert to an Instant and then convert that into a particular time zone.
I hope the first two lines of my solution below are helpful. My problem was I had a LocalDateTime and the name of a time zone, and I needed an instant so I could build a java.util.Date, because that's what MongoDB wanted. My code is Scala, but it's so close to Java here I think there should be no problem understanding it:
val zid = ZoneId.of(tzName) // "America/Los_Angeles"
val zo: ZoneOffset = zid.getRules.getOffset(localDateTime) // ⇒ -07:00
// 2017-03-16T18:03
val odt = OffsetDateTime.of(localDateTime, zo) // ⇒ 2017-03-16T18:03:00-07:00
val instant = odt.toInstant // ⇒ 2017-03-17T01:03:00Z
val issued = Date.from(instant)
The following returns the amount of time in milliseconds to add to UTC to get standard time in this time zone:
TimeZone.getTimeZone(ZoneId.of("Europe/Amsterdam")).getRawOffset()
I have an epoch second and a zoneId. Is there any way to convert ZoneId to ZoneOffset in java 8?
Get ZonedDateTime from epoch second and Zone Id
Get ZoneOffset from ZonedDateTime
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// Get ZonedDateTime from epoch second and Zone Id
ZonedDateTime zdt = Instant.ofEpochSecond(1597615462L).atZone(ZoneId.of("Europe/London"));
// Get ZoneOffset from ZonedDateTime
ZoneOffset offset = zdt.getOffset();
System.out.println(offset);
}
}
Output:
+01:00
Since you are looking for the default zone offset
ZonedDateTime.now().getOffset()
This does it without creating an Instant or such objects to pull it out.
public static ZoneOffset offset() {
return offset(ZoneId.systemDefault()); // Default system zone id
}
public static ZoneOffset offset(ZoneId id) {
return ZoneOffset.ofTotalSeconds((int)
TimeUnit.MILLISECONDS.toSeconds(
TimeZone.getTimeZone(id).getRawOffset() // Returns offset in milliseconds
)
);
}
Here is what we use. First convert zone id to timezone, then get the offset in millis, then convert to seconds, then create a ZoneOffset.
public static final ZoneOffset toOffset(ZoneId zoneId) {
return Optional.ofNullable(zoneId)
.map(TimeZone::getTimeZone)
.map(TimeZone::getRawOffset)
.map(Duration::ofMillis)
.map(Duration::getSeconds)
.map(Number::intValue)
.map(ZoneOffset::ofTotalSeconds)
.orElse(null);
}

How to save and retrieve Date in SharedPreferences

I need to save a few dates in SharedPreferences in android and retrieve it. I am building reminder app using AlarmManager and I need to save list of future dates. It must be able to retrieve as milliseconds. First I thought to calculate time between today now time and future time and store in shared preference. But that method is not working since I need to use it for AlarmManager.
To save and load accurate date, you could use the long (number) representation of a Date object.
Example:
//getting the current time in milliseconds, and creating a Date object from it:
Date date = new Date(System.currentTimeMillis()); //or simply new Date();
//converting it back to a milliseconds representation:
long millis = date.getTime();
You can use this to save or retrieve Date/Time data from SharedPreferences like this
Save:
SharedPreferences prefs = ...;
prefs.edit().putLong("time", date.getTime()).apply();
Read it back:
Date myDate = new Date(prefs.getLong("time", 0));
Edit
If you want to store the TimeZone additionaly, you could write some helper method for that purpose, something like this (I have not tested them, feel free to correct it, if something is wrong):
public static Date getDate(final SharedPreferences prefs, final String key, final Date defValue) {
if (!prefs.contains(key + "_value") || !prefs.contains(key + "_zone")) {
return defValue;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(prefs.getLong(key + "_value", 0));
calendar.setTimeZone(TimeZone.getTimeZone(prefs.getString(key + "_zone", TimeZone.getDefault().getID())));
return calendar.getTime();
}
public static void putDate(final SharedPreferences prefs, final String key, final Date date, final TimeZone zone) {
prefs.edit().putLong(key + "_value", date.getTime()).apply();
prefs.edit().putString(key + "_zone", zone.getID()).apply();
}
You can do this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
To save a date:
preferences .edit().putString("mydate", sdf.format(date)).apply();
To retrieve:
try{
Date date = sdf.parse(preferences.getString("myDate", "defaultValue"));
} catch (ParseException e) {
e.printStackTrace();
}
Hope it help.
tl;dr
The modern approach uses java.time classes and ISO 8601 strings.
Reading.
Instant // Represent a moment in UTC with a resolution of nanoseconds.
.ofEpochMilli(
Long.getLong( incomingText )
) // Returns a `Instant` object.
.atZone( // Adjust from UTC to some time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "Europe/Paris" )
) // Returns a `ZonedDateTime` object.
Writing.
ZonedDateTime
.of(
LocalDate.of( 2018 , Month.JANUARY , 23 ) ,
LocalTime.of( 15 , 35 ) ,
ZoneId.of( "Europe/Paris" )
) // Returns a `ZonedDateTime` object.
.toInstant() // Returns an `Instant`. Adjust from a time zone to UTC. Same moment, same point on the timeline, different wall-clock time.
.toEpochMilli() // Returns a `long` integer number primitive. Any microseconds or nanoseconds are ignored, of course.
If your alarm manager has not yet been modernized to handle java.time objects, convert between legacy & modern classes using new methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;
…and…
Instant instant = d.toInstant() ;
java.time
The troublesome old date-time classes were supplanted by the java.time classes.
For a moment in UTC, with a resolution of nanoseconds, use Instant.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
You want only milliseconds for your needs, so truncate any microseconds & nanoseconds.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ;
To determine a moment by date and time-of-day requires a time zone. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
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( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Combine with a time-of-day, a LocalTime.
LocalTime lt = LocalTime.of( 14 , 0 ) ;
Wrap it all together as a ZonedDateTime object.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust to UTC by extracting a Instant.
Instant instant = zdt.toInstant() ;
Extract your desired count-of-milliseconds since the epoch reference of first moment of 1970 in UTC. Again, be aware that any micros/nanos in your Instant will be ignored when extracting milliseconds.
long milliseconds = instant.toEpochMilli() ; // Be aware of potential data loss, ignoring any microseconds or nanoseconds.
Read those milliseconds back from storage as text using the Long class.
long milliseconds = Long.getLong( incomingText ) ;
Instant instant = Instant.ofEpochMilli( milliseconds ) ;
To see that moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To generate text representing that value, use DateTimeFormatter.ofLocalizedDateTime to automatically localize.
Tip: Consider writing your date-time values to storage in standard ISO 8601 format rather than as a count-of-milliseconds. The milliseconds cannot be read meaningfully by humans, making debugging & monitoring tricky.
String output = instant.toString() ;
2018-10-05T20:28:48.584Z
Instant instant = Instant.parse( 2018-10-05T20:28:48.584Z ) ;
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.

Categories