Getting unable to parse date exception - java

I have date and time on string type 20/03/2018, 18:20:44 Is it possible to change it to date format in java? I tried this code:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
Date date = formatter.parse(dateString);
return date;
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
I get unable to parse exception and returned with null

You've used the wrong string replacements inside your simple date format, it should be dd/MM/yyyy, HH:mm:ss. Note the capitalisation of the HH as well, your time is in 24 hour format so it must be HH over hh
So with the applied changes your code will look like this:
public static Date getDate(String dateString) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("PST"));
try {
return formatter.parse(dateString);
} catch (ParseException e) {
logger.error("error while parsing milliseconds to date" + dateString, e);
}
return null;
}
Read more on the various patterns available here, as an aside it is generally recommended to use the ISO 8601 format for dates, so yours would be yyyy-MM-ddTHH:mm:ss

You should use the same format with input string:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");

You did two mistakes :
mm represents minutes. MM represents months.
But You specify mm in the month part of the date format.
the coma character : , provided in the input has also to be present in the date format.
So with a String input in this form : "20/03/2018, 18:20:44", you should use this DateFormat :
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss");

tl;dr
Your formatting pattern was incorrect, using the wrong case and omitting the comma.
Also, you are using troublesome classes supplanted years ago by java.time classes.
LocalDateTime.parse( // Create a `LocalDateTime` object as the input string lacks any time zone or offset-from-UTC.
"20/03/2018, 18:20:44" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) // Define a formatting pattern to match the input.
)
.atZone( // Assign a time zone to the `LocalDateTime` to create a `ZonedDateTime` object.
ZoneId.of( "America/Los_Angeles" ) // Specify time zone to be assigned. Always use proper zone names `continent/region`; never use 3-4 character pseudo-zones.
)
2018-03-20T18:20:44-07:00[America/Los_Angeles]
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Parse your string as a LocalDateTime since it lacks an indicator of time zone or offset-from-UTC.
String input = "20/03/2018, 18:20:44" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu, HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2018-03-20T18:20:44
Lacking a time zone or offset-from-UTC means that this does not represent a moment, is not a point on the timeline. Without the context of a zone/offset, this represents only a vague idea about potential moments along a range of 26-27 hours.
Apparently you are certain this input was actually meant to be in certain time zone. Apply a ZoneId to this LocalDateTime to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Conversion
Best to avoid the troublesome legacy classes. But if you must produce a java.util.Date to inter-operate with old code not yet updated for java.time, you can convert. To convert back and forth, call new methods on the old classes.
A java.util.Date represents a point on the timeline in UTC, with a resolution of milliseconds. So its replacement in java.time is Instant. An Instant is also a point on the timeline in UTC, with a finer resolution of nanoseconds. To get to a Date, we need an Instant, which we can pull from our ZonedDateTime.
Instant instant = zdt.toInstant() ; // Same moment, same point on the timeline, different wall-clock time.
Now we can get the legacy class object, Date, by calling Date.from.
java.util.Date date = Date.from( instant ) ; // Do this only if you *must* work with `Date` 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.

Related

Java date parsing not working for ET timezone while working for IST

I am trying to parse the String to date. String having date format as
"dd-MMM-yyyy Z" and String having value "12-DEC-2018 ET". Its giving the error
java.text.ParseException: Unparseable date: "12-DEC-2018 ET".
The same code is working for String having value "12-DEC-2018 IST".
below is the code snippet:
public static void main(String[] args) throws ParseException {
String dateInputIST ="12-DEC-2018 IST";
String dateInputET ="12-DEC-2018 ET";
SimpleDateFormat sdfmt1 = new SimpleDateFormat("dd-MMM-yyyy Z");
SimpleDateFormat sdfmt2= new SimpleDateFormat("dd/MM/yyyy");
Date dDate = sdfmt1.parse( dateInputIST );
String strOutput = sdfmt2.format( dDate );
System.out.println(strOutput);
Date etDate = sdfmt1.parse(dateInputET);
strOutput = sdfmt2.format(etDate);
System.out.println(strOutput);
}
Could someone please help. I needed to parse the time in any timezone.
Thanks,
Navin
Change
String dateInputET ="12-DEC-2018 ET";
to
String dateInputET ="12-DEC-2018 EDT";
'ET' is not a recognized time zone.
Pseudo-zones
ET, EST, and IST are not actually time zones. Those 2-4 letter pseudo-zones are not standardized and are not even unique! For example, IST can mean India Standard Time, Ireland Standard Time, Iceland Standard Time, and more.
Real time zone names take the format of Continent/Region such as Africa/Tunis.
Date & zone, separately
Date with time zone has no real meaning.
Handle the date as a LocalDate object.
String input = "12-DEC-2018"
DayeTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Handle your desired time zone separately, as a ZoneId object.
ZoneId zNewYork = ZoneId.of( "America/New_York" ) ;
To combine, determine the first moment of the day.
ZonedDateTime zdtNewYork = ld.atStartOfDay( z ) ;
Generate text representing that moment in standard ISO 8601 format extended to append the name of the time zone in square brackets.
To see that same moment in UTC, extract a Instant.
Instant instant = zdtNewYork.toInstant() ;
Adjust into another zone.
ZonedDateTime zdtKolkata = instant.atZone( ZoneId.of( "Asia/Kolkata" ) ) ;
To focus on the date only, get a LocalDate for the day of that same moment when viewed through the lens of the wall-clock time used in India.
LocalDate ldKolkata = zdtKolkata.toLocalDate() ;
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.
java.time
DateTimeFormatter dateZoneFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uuuu v")
.toFormatter(Locale.ENGLISH);
String dateInputIST ="12-DEC-2018 IST";
String dateInputET ="12-DEC-2018 ET";
TemporalAccessor parsed = dateZoneFormatter.parse(dateInputIST);
System.out.println("Date: " + LocalDate.from(parsed) + " Time zone: " + ZoneId.from(parsed));
parsed = dateZoneFormatter.parse(dateInputET);
System.out.println("Date: " + LocalDate.from(parsed) + " Time zone: " + ZoneId.from(parsed));
On my computer the output from this snippet was:
Date: 2018-12-12 Time zone: Atlantic/Reykjavik
Date: 2018-12-12 Time zone: America/New_York
Format pattern letter v is for the generic time-zone name, that is, the name that is the same all year regardless of summer time (DST), for example Eastern Time or short ET.
If you want to control the interpretation of ambiguous time zone abbreviations (of which there are a lot), you may use the two-arg appendGenericZoneText​(TextStyle, Set<ZoneId>) where the second argument contains the preferred zones. Still better if there is a way for you to avoid relying on time zone abbreviations altogether since, as I said, they are very often ambiguous.
I am not sure what sense a date with a time zone makes, though.
As an additional point, always specify locale for your formatters so they will also work if the default locale is changed or one day your program runs in a JVM with a different default locale.
Avoid SimpleDateFormat and Date
I don’t think SimpleDateFormat will be able to parse your string. It’s just the same since that class is already long outdated and is renowned for being troublesome, so you should never want to use it anyway.

Discrepancy in java retaining time in milliseconds

I am trying to use mongodb to fetch some records with date fields, sample records are shown below, and want convert date field which has been parsed using jayway jsonpath to java.util.Date long integer. long integer converted does not match with the original one. Please help.
Sample records in tester collection:
{
"_id" : ObjectId("5b3fe6f91e618afb473dc644"),
"dateField" : ISODate("2018-07-06T15:46:55.819Z")
}
The Java code for getting records using jongo is as follows :
List<Tester> list= jongo.runCommand("{aggregate : 'tester',pipeline:[],cursor : {batchSize :10}}")
.field("cursor")
.as(Tester.class);
for(Tester t : list)
{
System.out.println("dateField test: : : : "+t.getDateField()+" : : : : "+t.getDateField().getTime());
// Output is perfectly fine : dateField test: : : : Fri Jul 06 21:16:55 IST 2018 : : : : 1530892015819
Gson gson = new Gson();
String str = gson.toJson(t);
DocumentContext docCtx = JsonPath.parse(str);
JsonPath jsonPath = JsonPath.compile("$.dateField");
Object obj = docCtx.read(jsonPath);
System.out.println(obj);
//After parsing with jsonPath the date is retained - Jul 6, 2018 9:16:55 PM
SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date d = format.parse(obj.toString());
System.out.println(d + " : : : " + d.getTime());
//Fri Jul 06 21:16:55 IST 2018 : : : 1530892015000 - Time is not retained
}
Expected :
t.getDateField().getTime() ==== d.getTime()
Please help
Regards
Kris
tl;dr
Your formatting pattern omits the fractional seconds, so no milliseconds appear in the output.
You are using obsolete date-time classes. Use java.time instead.
Example:
Instant // Represent a moment in UTC, with a resolution as fine as nanoseconds.
.parse( "2018-07-06T15:46:55.819Z" ) // Parse a string in standard ISO 8601 format. The `Z` on the end means UTC, pronounced “Zulu”.
.atZone( ZoneId.of( "Asia/Kolkata" ) ) // Adjust from UTC to a desired time zone. Same moment, same point on the timeline, different wall-clock time. Returns a `ZonedDateTime` object.
.toString() // Generate a String in standard ISO 8601 format. Represents the moment in our `ZonedDateTime` object.
Convert from legacy java.util.Date class to modern java.time.Instant, and back again. Example nonsense code:
java.util.Date.from( // Convert from modern `Instant` to legacy `Date`.
myJavaUtilDate.toInstant() // Convert from legacy `Date` to modern `Instant`.
)
java.time
You are using terribly troublesome old date-time classes: Date & SimpleDateFormat. These were supplanted years ago by the modern java.time classes.
Your input 2018-07-06T15:46:55.819Z is in standard ISO 8601 format. The java.time classes use the ISO 8601 formats by default when parsing or generating strings. So no need to specify a formatting pattern.
The Z on the end is pronounced Zulu and means UTC. The Instant class represents a moment in UTC.
Instant instant = Instant.parse( "2018-07-06T15:46:55.819Z" ) ;
Generate an output string in ISO 8601 format.
String output = instant.toString() ;
2018-07-06T15:46:55.819Z
Your code ignores the crucial issue of time zone. Rather than rely implicitly on the JVM’s current default time zone, be explicit with a ZoneId even if that is ZoneId.systemDefault().
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(!). For example, your IST could mean Irish Standard Time, India Standard Time, Iran Standard Time, or something else.
After adjusting from UTC to a specific time zone, we still have the same moment, the same point on the timeline. Only the wall-clock time is different.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ; // Or `ZoneId.systemDefault()`.
ZonedDateTime zdt = instant.atZone( z ) ; // Adjust from UTC to a specific time zone.
Generate an output string in ISO 8601 format extended to append the name of the time zone in square brackets.
String output = zdt.toString() ;
2018-07-06T21:16:55.819+05:30[Asia/Kolkata]
Notice your fractional second (milliseconds) is still intact.
Converting
Perhaps you must interface with an java.util.Date (your Question is not clear), because of old code not yet updated to support java.time.
You will find convenient conversion methods, new methods added to the old classes.
Going from java.util.Date to java.time.Instant.
Instant myInstant = myJavaUtilDate.toInstant() ;
Proceed as shown above. Adjust into your desired time zone, and generate a String.
Going the other direction, from the modern Instant class to the legacy class Date.
java.util.Date myDate = java.util.Date.from( myInstant ) ;
Immutable objects
The java.time classes are designed to be thread-safe, and use the immutable objects pattern. Notice how the code above produces fresh objects based on the original’s values, rather than altering (“mutating”) the original.
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.
new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
You are discarding the milliseconds part of the input, which results in exactly the difference you see. Use this instead:
new SimpleDateFormat("MMM dd, yyyy hh:mm:ss.SSS aaa");
^^^^

Format a Date String with Time zone and return Date object

I need to format a string date with given time zone and return the date object back. I am currently in IST time zone.
So IST is 5 hours and 30 minutes ahead of UTC.
public void getDate(){
String dateStr = "11/25/2016T13:30:00.000";
String dateFormat = "MM/dd/yyyy'T'HH:mm:ss.SSS";
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(date);
}
public static Date formatedStringToDate(final String date, final String dateFormat) throws ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsedDate = null;
if (date != null) {
try {
parsedDate = sdf.parse(date);
} catch (ParseException e) {
throw e;
}
}
return parsedDate;
}
I get the below out put.
Fri Nov 25 19:00:00 **IST** 2016
The time seems to be change from 5.30 hours but then if its a IST to UCT time converstion, it should be 5.30 hours before 13:30:00 which is 08:00:00?
Also how could I change the highlighted IST part of out put string to show the currect time zone in this case UTC?
When you call toString on a Date (by printing it) you get the default format (because a Date is an object that stores a number of milliseconds, or nanoseconds in Java 9+, since an epoch). To see the result in UTC you need something like,
final DateFormat sdf = DateFormat.getDateTimeInstance(DateFormat.FULL,
DateFormat.FULL);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatedStringToDate(dateStr, dateFormat);
System.out.println(sdf.format(date)); // <-- format the Date
tl;dr
LocalDateTime.parse( "2017-11-25T13:30:00.000" )
.atZone( ZoneId.of( "Asia/Kolkata" ) )
2017-11-25T13:30+05:30[Asia/Kolkata]
java.time
The modern approach uses the java.time classes that replaced the troublesome old legacy date-time classes.
Parse your input string as a LocalDateTime given the lack of any indicator of zone or offset-from-UTC.
Using standard ISO 8601 format for such strings is preferred. The java.time classes use the standard formats by default when parsing/generating strings.
LocalDateTime ldt = LocalDateTime.parse( "2017-11-25T13:30:00.000" ) ;
ldt.toString(): 2017-11-25T13:30
If you are certain this date-time was intended to represent a moment by the wall-clock time of India, then assign a time zone to produce a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2017-11-25T13:30+05:30[Asia/Kolkata]
You can adjust into another zone for comparison.
ZonedDateTime zdtMontreal = zdt.withZoneSameInstant( ZoneId.of( "America/Montreal") );
zdtMontreal.toString(): 2017-11-25T03:00-05:00[America/Montreal]
To parse/generate strings in other formats such as the one in your Question, use the DateTimeFormatter or DateTimeFormatterBuilder classes. Search Stack Overflow for more info, as these have been covered extensively.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu'T'HH:mm:ss.SSS" , Locale.US ) ;
Use that formatter for parsing.
LocalDateTime ldt = LocalDateTime.parse( "11/25/2016T13:30:00.000" , f ) ;
And for generating.
String output = ldt.format( f ) ; // Generate string.
Consider using ISO 8601 formats instead.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to Format ISO-8601 in Java

I am trying to change from standard ISO 8601 format 2014-09-11T21:28:29.429209Z into a nice MMM d yyyy hh:mm z format, however my current code is failing.
public void setCreatedAt( String dateTime ) {
LocalDate newDateTime = LocalDate.parse(dateTime);
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a z");
createdAt = newDateTime.format(format);
}
catch (Exception e) {
}
}
I am receiving the time and date from an api.
A java.time.LocalDate is "a date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03" so there is not enough information there. Use java.time.ZonedDateTime instead.
Also, swallowing exceptions like that makes it much harder to troubleshoot. When you don't intend to handle an exception either don't catch it at all, catch and re-throw it wrapped in a RuntimeException or at the very least log it (e.printStackTrace() or similar) .
tl;dr
Instant.parse( "2014-09-11T21:28:29.429209Z" )
.atZone( ZoneId.of( "Asia/Kolkata" ) )
.format( DateTimeFormatter.ofPattern("MMM d uuuu hh:mm a z" , Locale.US ) )
See this code run live at IdeOne.com.
Details
The Answer by Jakber will work technically but is misleading.
ZonedDateTime is for time zones
A ZonedDateTime is meant to have an assigned time zone such as America/Montreal or Pacific/Auckland.
But this input string lacks a time zone. The Z on the end is short for Zulu and means UTC, or in other words, an offset-from-UTC of zero hours, +00:00.
A time zone is a historical collection of offsets for a particular region with rules for upcoming changes to the offset for anomalies such as Daylight Saving Time (DST).
Instant
The input string is better parsed as an Instant which represents a moment on the timeline always in UTC. This class directly parses such strings in that particular standard ISO 8601 format, so no need for formatting pattern.
Instant instant = Instant.parse( "2014-09-11T21:28:29.429209Z" );
Adjust into time zone
You can adjust into a time zone to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z );
Generating string
To generate a string in the same format as input, simply call Instant::toString().
String output = instant.toString() ;
For your custom format using the wall-clock time of a region, use DateTimeFormatter with your custom formatting pattern. And your ZonedDateTime. As a good habit, always specify the desired Locale used for the human language in translation and cultural norms in formatting.
DateTimeFormatter f = DateTimeFormatter.ofPattern("MMM d uuuu hh:mm a z" , Locale.US );
String output = zdt.format( f );
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.
public void setCreatedAt(String dateTime) {
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
SimpleDateFormat sdfTarget = new SimpleDateFormat("MMM d yyyy hh:mm a z", Locale.getDefault());
try {
Date date = sdfSource.parse(dateTime);
String createdAt = sdfTarget.format(date);
Log.e(TAG, "setCreatedAt: createdAt " + createdAt);
} catch (ParseException e) {
e.printStackTrace();
}
}

Reading system time in CST time zone using Java

I am trying to read the system date in CST time zone using Java. I tried the below code but whenever I use formatter.parse() it is returning time in EST time zone.
private Date getTodayInCST() {
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("CST");
formatter.setTimeZone(obj);
String today = formatter.format(currentdate.getTime());
try {
return formatter.parse(today);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
tl;dr
ZonedDateTime.now(
ZoneId.of( "America/Chicago" )
)
Details
I am trying to read the system date in CST time zone
By “CST”, do you mean Central Standard Time in North America, or China Standard Time?
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 as seen above with CST.
ZoneId z = ZoneId.of( "America/Chicago" ) ;
java.time
You are using troublesome old date-time classes that are now legacy. Supplanted by the java.time classes.
Get the current moment in UTC. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ;
2018-02-26T05:45:24.213610Z
Adjust into another time zone. Same moment, same point on the timeline, different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-02-25T23:45:24.213610-06:00[America/Chicago]
The above strings are in standard ISO 8601 format. The ZonedDateTime class extends that standard wisely to append the name of the zone in square brackets.
If you want to generate String objects in other formats, use DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
String output = zdt.format( f ) ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
If you want to set timezone try it this way
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
format.setTimeZone(TimeZone.getTimeZone("CST"));
System.out.println(format.format(new Date()));
If want to the code to provide the current time considering the daylight saving adjustment from CST to CDT or vice versa ,you can use the
"CST6CDT" timezone. in place of "CST" in SimpleDateFormat.
SimpleDateFormat cstCdtFormat=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
cstCdtFormat.setTimeZone(TimeZone.getTimeZone("CST6CDT"));
System.out.println(cstCdtFormat.format(new Date()));

Categories

Resources