Query a Table based on the column as datetime2(7) from JPA - java

I need to query list of records between the given date range based on the column which was defined as datetime2(7) in MS SQL Server.
From the HTTP request I will be receiving startDate and endDate as below.
http://{host:port}/api/records/date?startDate=**2021-05-31T14:12:44.8020000**&endDate=**2021-05-31T14:12:44.8020000**
In the database, value in lastUpdated column is stored as 2021-05-31 14:12:44.8020000
I am trying to convert the incoming query params which is a String to java.sql.Date in the code as below
#Override
public Page<Entity> getAllRecordsWithDateRange(String startDate, String endDate) {
Page<Entity> recordsWithinDateRange = null;
String time = startDate;
String formatIn = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS";
String formatOut = "yyyy-MM-dd HH:mm:ss.SSSSSS";
SimpleDateFormat in = new SimpleDateFormat(formatIn);
SimpleDateFormat out = new SimpleDateFormat(formatOut);
Date dateIn = null;
try {
dateIn = in.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
String valueOut = out.format(dateIn);
System.out.println(">>> " + valueOut);
Pageable page = PageRequest.of(0,5000);
Date date1= null;
try {
date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse(valueOut);
java.util.Date utilDate = date1;
recordsWithinDateRange = repo.getAllRecordsBetweenDates(utilDate,utilDate,page);
} catch (ParseException e) {
e.printStackTrace();
}
return recordsWithinDateRange;
}
Issue I am seeing here is my actual input date is 2021-05-31T14:12:44.8020000
But, after the conversion it is incremented to a different time 2021-05-31 16:26:24.000000. So, query is returning no records from the DB.
Could someone help me to solve this issue? TIA!

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API*:
datetime2 maps to TIMESTAMP ANSI SQL type or LocalDateTime in JDBC.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d'T'H:m:s.SSSSSSS", Locale.ENGLISH);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSSSSS", Locale.ENGLISH);
String strDateTime = "2021-05-31T14:12:44.8020000";
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtfInput);
System.out.println(ldt.format(dtfOutput));
}
}
Output:
2021-05-31 14:12:44.8020000
ONLINE DEMO
Check this answer to learn how to perform JDBC operations using LocalDateTime.
Solution using legacy API:
SimpleDateFormat does not handle fraction-of-second beyond millisecond precision correctly. Check this answer to learn more about it.
You need to truncate the date-time string to millisecond precision.
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "2021-05-31T14:12:44.8020000";
strDateTime = strDateTime.substring(0, strDateTime.indexOf('.') + 4);
String formatIn = "yyyy-MM-dd'T'HH:mm:ss.SSS";
String formatOut = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat in = new SimpleDateFormat(formatIn);
SimpleDateFormat out = new SimpleDateFormat(formatOut);
System.out.println(out.format(in.parse(strDateTime)));
}
}
Output:
2021-05-31 14:12:44.802
ONLINE DEMO
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Related

Java Convert String and Long to DateTime

I would like to generate a DateTime variable from two different variables (get the date from myLongDateAndTime and time from myStringTime, how can I do that?
String myStringTime="12:30:10"; // Come from DB
long myLongDateAndTime= 1628197200000 // Come from another DB stores date and times in timestamp format of Thu Aug 05 2021 17:00:00 GMT-0400
DateTime myDateTime=??? // should get Thu Aug 05 2021 12:30:10
java.time
Quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
Instant instant = Instant.ofEpochMilli(myLongDateAndTime);
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-04:00"));
System.out.println(odt);
odt = odt.with(time);
System.out.println(odt);
}
}
Output:
12:30:10
2021-08-05T21:00:00Z
2021-08-05T17:00-04:00
2021-08-05T12:30:10-04:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness
Just for the sake of completeness, given below is the solution using the Joda Date-Time API:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
DateTime dateTime = new DateTime(Long.valueOf(myLongDateAndTime), DateTimeZone.forOffsetHours(-4));
System.out.println(dateTime);
dateTime = dateTime.withTime(time);
System.out.println(dateTime);
}
}
Output:
12:30:10.000
2021-08-05T17:00:00.000-04:00
2021-08-05T12:30:10.000-04:00
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You are combining two dates, so what you need to do is:
create a joda DateTime from the long
format that DateTime to a string with only the date part
combine with date string and time string in a single string
parse the new string
and here is how you can do that:
public DateTime combineDates(long myLongDateAndTime, String myStringTime) {
// 1 - create DateTime from the long
DateTime dateFromLong = new DateTime(myLongDateAndTime);
// 2 - Format dateFromLong as date string
DateTimeFormatter dtfDate = DateTimeFormat.forPattern("dd/MM/yyyy");
String dateString = dtfDate.print(dateFromLong);
// 3 - Concatenate date part and time part in a new string
String completeDate = dateString + " " + myStringTime;
// 4 - Parse the new string in to a DateTime
DateTimeFormatter dtfDateTime =
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
return dtfDateTime.parseDateTime(completeDate);
}
This is only a possible solution. There are many other ways to do the same, for example without using a string concatenation, but only dates operations, but this way is quite clear and readable, so I don't investigate additional possible solutions.
One possible solution:
public class TestSample {
public static void main(String[] args) {
String myStringTime="12:30:10";
Long myLongDateAndTime= 1628197200000L;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
LocalTime time = LocalTime.parse(myStringTime, formatter);
LocalDate date = Instant.ofEpochMilli(myLongDateAndTime).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime dtTime = LocalDateTime.parse(date.toString()+" "+time.toString(), formatter1);
System.out.println(dtTime.toString());
}
}

How to solve parse exception when timezone has colon?

I am receiving DateTime as a String from a webservice. An example of this DateTime string is: "DateTime":"2021-06-06T04:54:41-04:00".
This 2021-06-06T04:54:41-04:00 more or less matches the ISO-8601 format, so I have used this pattern to parse it: yyyy-MM-dd'T'HH:mm:ssZ. However, the colon in the timezone part of the response DateTime is causing issues. 2021-06-06T04:54:41-04:00 is giving parse exception, but 2021-06-06T04:54:41-0400 is parsing fine.
Below code should explain it better:
public void stringToDate() {
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ"; //ISO - 8601 Format
TimeZone timeZoneEST = TimeZone.getTimeZone("US/Eastern");
SimpleDateFormat sdf = new SimpleDateFormat(pattern, new Locale("en", "US"));
sdf.setLenient(false);
sdf.setTimeZone(timeZoneEST);
String timeFromWebService = "2021-06-06T04:54:41-04:00";
try {
Date parsedDate = sdf.parse(timeFromWebService); // not working because of colon in timezone part
System.out.println(parsedDate);
} catch (ParseException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000); //sleep to avoid interleaving output from stacktrace (above) and syso (below)
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String timeFromWebServiceModified = "2021-06-06T04:54:41-0400"; //removed colon from timezone part
try {
Date parsedDate = sdf.parse(timeFromWebServiceModified); // working because colon is removed in timezone part
System.out.println(parsedDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
I want to handle this parsing without modifying the response DateTime. Any suggestions on how I can parse the original DateTime. Any suggestion on what pattern to use will be very help full.
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d'T'H:m:s[XXX][XX][X]", Locale.ENGLISH);
//Test
Stream.of(
"2021-06-06T04:54:41-04:00",
"2021-06-06T04:54:41-0400",
"2021-06-06T04:54:41-04",
"2021-06-06T04:54:41Z"
).forEach(s -> System.out.println(OffsetDateTime.parse(s, dtf)));
}
}
Output:
2021-06-06T04:54:41-04:00
2021-06-06T04:54:41-04:00
2021-06-06T04:54:41-04:00
2021-06-06T04:54:41Z
ONLINE DEMO
Check How to use OffsetDateTime in JDBC?.
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
Solution using legacy API:
SimpleDateFormat does not have a feature to specify optional patterns, the way we do, using the square bracket, with DateTimeFormatter. In this case, you can create multiple instances of SimpleDateFormat and try with each one.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sfdArr[] = {
new SimpleDateFormat("y-M-d'T'H:m:sXXX", Locale.ENGLISH),
new SimpleDateFormat("y-M-d'T'H:m:sXX", Locale.ENGLISH),
new SimpleDateFormat("y-M-d'T'H:m:sX", Locale.ENGLISH)
};
String []strDateTimeArr = {
"2021-06-06T04:54:41-04:00",
"2021-06-06T04:54:41-0400",
"2021-06-06T04:54:41-04",
"2021-06-06T04:54:41Z"
};
for(String s : strDateTimeArr) {
Date date = null;
for(SimpleDateFormat sdf : sfdArr) {
try {
date = sdf.parse(s);
}catch(ParseException e) {
//...
}
}
System.out.println(date);
}
}
}
ONLINE DEMO
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How can I retrieve datetiime from mongodb? By comparing the data with jDateChosser Java

private void showdataTable_btnActionPerformed(java.awt.event.ActionEvent evt) {
try {
DateFormat df = new SimpleDateFormat("YYYY-mm-dd'T'HH:MM:ss'Z'"); //set date format
String set = df.format(dateChoos1.getDate()); //add value to set
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("datetimes", set); //where date via set(date)
DBCursor cursor = table.find(whereQuery);
while (cursor.hasNext()) {
DBObject obj = cursor.next();
String ip_address = (String) obj.get("ip_address");
String mac_address = (String) obj.get("mac_address");
Date datetimes = (Date) obj.get("datetimes");
String url = (String) obj.get("url");
model.insertRow(model.getRowCount(), new Object[]{datetimes, ip_address, mac_address, url});
}
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
Your format, YYYY-mm-dd'T'HH:MM:ss'Z' is not correct. Let's discuss everything which is wrong with this format.
You have used Y instead of y: The symbol Y is used for Week year while y is used for Year. Check Difference between year-of-era and week-based-year? to learn more about it.
You have used mm for month: The correct symbol for the month is M.
You have used MM for minutes: The correct symbol for the minute is m.
You have enclosed Z within single quotes: The symbol, Z is used for Time zone whereas 'Z' is nothing but a character literal. Probably you want to format the timezone offset of +00:00 as Z and for this, you should in fact use X.
So, the correct format is as follows:
yyyy-MM-dd'T'HH:mm:ssX
A demo with the suggested format:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
System.out.println(sdf.format(date));
}
}
Output:
2021-01-14T08:13:01Z
Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Use Date#toInstant to convert a java.util.Date object (the legacy type) to java.time.Instant (the modern type). Instant represents an instantaneous point on the time-line and should be just enough for most of your JSON operations. The Instant#toString returns the date-time string with UTC timezone offset which is compliant with ISO-8601 standards.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Instant instant = date.toInstant();
// Print the value of instant#toString
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
System.out.println(odt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
System.out.println(dtf.format(odt));
}
}
Output:
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35Z

Java SimpleDateFormat decrementing date by one day

I am trying to reformat a date string using sdf. SDF is decrementing the date by a day. Pointers would be helpful.
java version "1.8.0_31"
Input: ChangeDateStringFormat("10-Mar-2015");
Code:
public static String ChangeDateStringFormat (String Input) throws InterruptedException
{
System.out.print("Input Date inside ChangeDateStringFormat : " + Input );
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("MST"));
System.out.print(" || Output Date inside ChangeDateStringFormat : " + sdf.format(new Date(Input)) + "\n");
return sdf.format(new Date(Input));
}
Output Actual:
Input Date inside ChangeDateStringFormat : 10-Mar-2015 || Output Date inside ChangeDateStringFormat : Mar-09-2015
Output I was Expecting :
Input Date inside ChangeDateStringFormat : 10-Mar-2015 || Output Date inside ChangeDateStringFormat : Mar-10-2015
This is the problem:
new Date(Input)
You should not use that. Instead, construct a SimpleDateFormat to parse your input:
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws ParseException {
System.out.println(convertDateFormat("10-Mar-2015"));
}
public static String convertDateFormat(String input) throws ParseException {
TimeZone zone = TimeZone.getTimeZone("MST");
SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
inputFormat.setTimeZone(zone);
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-dd-yyyy", Locale.US);
outputFormat.setTimeZone(zone);
Date date = inputFormat.parse(input);
return outputFormat.format(date);
}
}
However:
If you're just parsing a date, you'd be better of specifying UTC as the time zone; you don't want to end up with problems due to time zones that switch DST at midnight
If you're going to run this code on Java 8 and nothing lower, I'd strongly recommend using java.time instead of Date, Calendar etc.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(changeDateStringFormat("10-Mar-2015"));
}
static String changeDateStringFormat(String input) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d-MMM-u", Locale.ENGLISH);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMM-dd-uuuu", Locale.ENGLISH);
LocalDate date = LocalDate.parse(input, dtfInput);
return date.format(dtfOutput);
}
}
Output:
Mar-10-2015
ONLINE DEMO
Note: Never use SimpleDateFormat or DateTimeFormatter without a Locale.
Learn more about the modern Date-Time API from Trail: Date Time.
Side Note: Always follow Java naming conventions e.g. the name of your function should be changeDateStringFormat instead of ChangeDateStringFormat and the parameter Input should be named as input.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Timezone conversion for a specific datetime in java

I will be giving input date time for a timezone and the timezone for the input date time and we want the relevant DateTime in the expected timezone.
And here is my method.
convertToTimezone("03/08/2010 20:19:00 PM","Asia/Shanghai","US/Central");
The above time is the time in Asia/Shanghai. We would like to know what is the corresponding time in US/Central.
It's working fine but I am getting a 1-hour difference from the actual time.
Can I know where I am going wrong?
Here is the code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class DateUtil {
private static String format_date = "MM/dd/yyyy HH:mm:ss a";
public static void main(String a[]) {
try {
String sourceTimezone = "Asia/Shanghai";
String destTimezone = "US/Central";
String outputExpectedTimezone = convertToTimezone("03/08/2010 20:19:00 PM", sourceTimezone, destTimezone);
System.out.println("outputExpectedTimezone :" + outputExpectedTimezone);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone)
throws Exception {
String outputDate = null;
SimpleDateFormat format = new SimpleDateFormat(format_date);
format.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(inputDateTimezone));
calendar.setTime(format.parse(inputDate));
calendar.add(Calendar.MILLISECOND, -(calendar.getTimeZone().getRawOffset()));
calendar.add(Calendar.MILLISECOND, -calendar.getTimeZone().getDSTSavings());
calendar.add(Calendar.MILLISECOND, TimeZone.getTimeZone(destinationDateTimezone).getRawOffset());
outputDate = format.format(calendar.getTime());
return outputDate;
}
}
You shouldn't be adding anything to the calendar - that represents a specific instant in time. In fact, you don't need a calendar at all.
Instead, have two different formats, one for each time zone:
public static String convertToTimezone(String inputDate,
String inputDateTimezone,
String destinationDateTimezone)
throws Exception
{
SimpleDateFormat parser = new SimpleDateFormat(format_date);
parser.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Date date = parser.parse(inputDate);
SimpleDateFormat formatter = new SimpleDateFormat(format_date);
formatter.setTimeZone(TimeZone.getTimeZone(outputDateTimezone));
return formatter.format(date);
}
As an aside, I'd thoroughly recommend using Joda Time instead of the built-in date/time API.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
Since your input Date-Time does not have timezone information, parse it into a LocalDateTime
Attach the timezone of the input Date-Time with it to get a ZonedDateTime
Use the ZonedDateTime#withZoneSameInstant to convert this ZonedDateTime to the target ZonedDateTime
Return the formatted target ZonedDateTime.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "US/Central"));
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "America/Mexico_City"));
}
static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(inputDate, dtf);
ZonedDateTime zdtInput = ldt.atZone(ZoneId.of(inputDateTimezone));
ZonedDateTime zdtDestination = zdtInput.withZoneSameInstant(ZoneId.of(destinationDateTimezone));
return zdtDestination.format(dtf);
}
}
Output:
03/08/2010 06:19:00 AM
03/08/2010 06:19:00 AM
ONLINE DEMO
Note: Avoid using the deprecated ID, US/Central. Use the standard ID, America/Mexico_City where Mexico City is the largest city in this timezone.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Categories