This question already has answers here:
Java string to date conversion
(17 answers)
Closed 6 years ago.
I am trying to parse this date with SimpleDateFormat and it is not working:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Formaterclass {
public static void main(String[] args) throws ParseException{
String strDate = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date dateStr = formatter.parse(strDate);
String formattedDate = formatter.format(dateStr);
System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
Date date1 = formatter.parse(formattedDate);
formatter = new SimpleDateFormat("dd-MMM-yyyy");
formattedDate = formatter.format(date1);
System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
}
}
If I try this code with strDate="2008-10-14", I have a positive answer. What's the problem? How can I parse this format?
PS. I got this date from a jDatePicker and there is no instruction on how modify the date format I get when the user chooses a date.
You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):
SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
String input = "Thu Jun 18 20:56:02 EDT 2009";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(date);
...
JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
We now have a more modern way to do this work.
java.time
The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.
Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.
By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.
String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );
Dump to console.
System.out.println ( "zdt : " + zdt );
When run.
zdt : 2009-06-18T20:56:02-04:00[America/New_York]
Adjust Time Zone
For fun let's adjust to the India time zone.
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );
zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]
Convert to j.u.Date
If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");
The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"
In response to:
"How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate
Try this:
With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.
public static void main(String[] args) throws ParseException {
String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
Date f = new Date(fecha);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
fecha = sdf.format(f);
System.out.println(fecha);
}
Related
This question already has answers here:
java DateTimeFormatterBuilder fails on testtime [duplicate]
(2 answers)
Closed 2 years ago.
I have a pdf file where I want to know if the next line is a date, or just a string (there are two types of formats of the listing, and knowing if I've arrived at a date is important.) The trouble is, there appears to be no way to use date formatting to arrive at a date of 01 Apr 2020
LocalDate date = parseDate( "dd MMM yyyy", "01 Apr 2020" );
Throws ... Text '01 Apr 2020' could not be parsed at index 3
private static LocalDate parseDate( final String format, final String s ) {
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format );
LocalDate ld; // Check if this was a legal LocalDate.
try {
ld = LocalDate.parse(s, df);
} catch (java.time.format.DateTimeParseException pe) {
System.out.println( pe.getMessage() );
ld = null; // This will signal an error
}
return ld;
}
Is there really no way to parse that format of date, like a bank uses in their pdf?
Replace
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format );
With
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format , Locale.US );
Hopefully, this will resolve your issue.
I believe you're using java8, You can do
LocalDate date = LocalDate.parse("01 Apr 2020", DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ROOT));
Edited: After pointed out that it doesn't work for all locales. Locale.ROOT should be used for neutral locale.
This question already has answers here:
Parsing ISO_INSTANT and similar Date Time Strings
(4 answers)
Java / convert ISO-8601 (2010-12-16T13:33:50.513852Z) to Date object
(4 answers)
Closed 5 years ago.
I'm using the Guardian API to get recent news stories about football.
I want to show date and time info to the user, but not in the format the API throws it back to me.
When requesting webPublicationDate after querying http://content.guardianapis.com/search?page-size=10§ion=football&show-tags=contributor&api-key=test I get the response in this format:
2017-06-22T16:18:04Z
Now, I want the date and time info in this format:
e.g. Jun 21, 2017 and 16:18 or 4:18 pm.
While I basically know to format a Date object properly into this format:
/**
* Return the formatted date string (i.e. "Mar 3, 1984") from a Date object.
*/
private String formatDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("LLL dd, yyyy");
return dateFormat.format(dateObject);
}
/**
* Return the formatted date string (i.e. "4:30 PM") from a Date object.
*/
private String formatTime(Date dateObject) {
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
return timeFormat.format(dateObject);
}
But I can't seem to convert the response I get into a Date object.
You can format the text this way:
package com.mkyong.date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateExample5 {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateInString = "2014-10-05T15:23:01Z";
try {
Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
System.out.println(date);
System.out.println("time zone : " + TimeZone.getDefault().getID());
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Z suffix means UTC, java.util.SimpleDateFormat doesn’t parse it correctly, you need to replace the suffix Z with ‘+0000’.
Code from here: https://www.mkyong.com/java/how-to-convert-string-to-date-java/
Instead of directly working with SimpleDateFormat (as this old API has lots of problems and design issues), you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To use it in Android, you'll also need the ThreeTenABP (more on how to use it here).
The main classes to be used are org.threeten.bp.ZonedDateTime (which can parse the date/time input) and org.threeten.bp.format.DateTimeFormatter (to control the output format).
If you are reading this field (2017-06-22T16:18:04Z) as a String, you can create a ZonedDateTime like this:
ZonedDateTime z = ZonedDateTime.parse("2017-06-22T16:18:04Z");
If you already have a java.util.Date object, you can convert it using org.threeten.bp.DateTimeUtils with a org.threeten.bp.ZoneOffset:
Date date = // get java.util.Date
ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneOffset.UTC);
In the end, the ZonedDateTime object will have the webPublicationDate value.
To get the different output formats, just create one DateTimeFormatter for each format. In the examples below, I also use java.util.Locale class to make sure the month names are in English:
// for Mar 3, 1984
DateTimeFormatter f1 = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);
// for 4:40 PM
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
// for 16:18
DateTimeFormatter f3 = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
System.out.println(f1.format(z)); // Jun 22, 2017
System.out.println(f2.format(z)); // 4:18 PM
System.out.println(f3.format(z)); // 16:18
The output is:
Jun 22, 2017
4:18 PM
16:18
Note that it uses the UTC timezone (the Z in 2017-06-22T16:18:04Z). If you want to display the date and time in another timezone, just use the org.threeten.bp.ZoneId class:
System.out.println(f3.format(z.withZoneSameInstant(ZoneId.of("Europe/London")))); // 17:18
The output is 17:18 (becase London is in summer time now).
Note that the API uses IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard. To find the timezone that better suits each region, use the ZoneId.getAvailableZoneIds() method and check which one fits best for your use cases.
If you don't want to add another dependency to your project and use SimpleDateFormat, you do something similar (create one parser and 3 output formatters, and use English locale). Also don't forget to set the timezone - I'm using UTC below, but you can change it to whatever timezone you want.
// parse date
String dateInString = "2017-06-22T16:18:04Z";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse(dateInString);
// create output formatters (set timezone to UTC)
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat s1 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
s1.setTimeZone(utc);
SimpleDateFormat s2 = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
s2.setTimeZone(utc);
SimpleDateFormat s3 = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
s3.setTimeZone(utc);
System.out.println(s1.format(date));
System.out.println(s2.format(date));
System.out.println(s3.format(date));
The output will be the same:
Jun 22, 2017
4:18 PM
16:18
I want this date to be displayed in GMT "01/01/2100"
Expecting result - "Fri Jan 01 00:00:00 GMT 2100"
Result i am seeing - "Thu Dec 31 19:00:00 EST 2099"
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try{
Date myDate = sdf.parse("01/01/2100");
System.out.println(myDate);
}
catch(Exception e){
}
I want the result myDate in GMT time not EST
Example 2
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("gmt"));
try{
Date myDate = sdf.parse("2010-05-23 09:01:02");
SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
System.out.println("MYDATE: " +df.format(myDate));
}
catch(Exception e){
}
Output: Sun, 23 May 2010, 05:01
Expecting: Sun, 23 May 2010, 09:01
http://goo.gl/uIy9RQ - URL for my project code, run and check the result
As already stated in the comments you have to apply the date format to the Date. I modified your code to display the myDate
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date myDate = sdf.parse("01/01/2100");
System.out.println(sdf.format(myDate));
sdf.setTimeZone(TimeZone.getTimeZone("EST"));
System.out.println(sdf.format(myDate));
}
catch(Exception e){
// error handling
}
Output is
01/01/2100
31/12/2099
But do not forget the date still contains information about hours, minutes, seconds etc. In respect to the applied date formatter this information is not shown when running
System.out.println(sdf.format(myDate));
If you need to set some fields of the date, you should make use of the Calendar.
For customizing date format use below
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());
Date format parameter can be any one of the following
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
toString on java.util.Date Is Misleading
As has been stated many times before on Stack Overflow, the toString method of java.util.Date silently applies the JVM’s current default time zone when generating the textual representation of the date-time value. An unfortunate design choice.
The old java.util.Date/.Calendar classes are notoriously troublesome. Avoid them. In Java 8 and later, use the built-in java.time framework. Defined by JSR 310, extended by the ThreeTen-Extra project. See Tutorial.
UTC
Basically UTC is the same as GMT in this context.
java.time
The java.time framework includes the class LocalDate for a date-only value without time-of-day nor time zone.
Note that getting the current date requires a time zone even though no time zone is stored internally. For any given moment the date varies around the world by time zone, with a new day dawning earlier in the east.
Use a proper time zone name. Never use 3-4 letter codes such as EST as they are neither standardized nor unique.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
The LocalDate::toString method generates a string in standard ISO 8601 format: 2016-01-23.
Joda-Time
If Java 8 technology is not available to you, add the very successful Joda-Time library. Joda-Time inspired the java.time.
In this case the code is similar that seen above.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
LocalDate localDate = new LocalDate( zone );
I have tried many different types of solutions using java.text.SimpleDateFormat but couldn't quite get it right.
The input string I receive is Tue Nov 5 00:00:00 UTC+0530 2013.
The format that I want is dd-MMM-yy.
Below is the code that I use:
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
date = formatter.parse(s);
System.out.println(date);
I receive an error: unreported exception ParseException; must be caught or declared to be thrown
date = formatter.parse(s);
I tried a lot of change in my formats but still I receive this error. Can anyone please let me know the exact format of the string that I am passing?
Handle Exceptions
You have not handled exceptions in your code. That is why the compiler gives errors. You need to handle the ParseException that may be thrown during parsing.
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
try{
date = formatter.parse(s);
System.out.println(date);
}catch(ParseException ex){
//exception
ex.printStackTrace();
}
Or you can add throws ParseException to your method .
According to your comment it seems to be you are trying to convert a date[String] to another format. If I am correct then the following example may help you.
String inputstring="Tue Nov 5 00:00:00 UTC+0530 2013";
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
DateFormat outformat = new SimpleDateFormat("dd-MMM-yy");
try {
String result = outformat.format(formatter.parse(inputstring));
System.out.println(result);
} catch (ParseException ex) {
ex.printStackTrace();
}
Output:
04-Nov-13
No Problem
Your code works* if you catch the exception as directed in the correct answer.
String input = "Tue Nov 5 00:00:00 UTC+0530 2013";
java.text.SimpleDateFormat sdformatter = new java.text.SimpleDateFormat( "EEE MMM d HH:mm:ss zZ yyyy" , Locale.ENGLISH );
java.util.Date date = null;
try {
date = sdformatter.parse( input );
} catch ( ParseException ex ) {
System.out.println( "ERROR: " + ex ); // … handle exception
}
System.out.println( "date: " + date + " (adjusted to Kolkata time via Joda-Time: " + new DateTime( date , DateTimeZone.forID( "Asia/Kolkata" ) ) );
When run.
date: Mon Nov 04 10:30:00 PST 2013 (adjusted to Kolkata time via Joda-Time: 2013-11-05T00:00:00.000+05:30
Joda-Time
That same format works in Joda-Time 2.5.
The java.util.Date/.Calendar/java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the new java.time package built into Java 8 (inspired by Joda-Time).
String input = "Tue Nov 5 00:00:00 UTC+0530 2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM d HH:mm:ss zZ yyyy" );
DateTime dateTime = formatter.parseDateTime( input ).withZone( DateTimeZone.forID( "Asia/Kolkata" ) );
System.out.println( "dateTime: " + dateTime );
When run.
dateTime: 2013-11-05T00:00:00.000+05:30
Alternate Format
In your case, you could ignore the UTC as it is redundant with the offset ( +0530 ). An offset is assumed to be from UTC. You can ignore characters by using quote marks.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM d HH:mm:ss 'UTC'Z yyyy" );
*Your code works for me using Java 8 Update 25. Earlier versions of java.text.SimpleDateFormat had varying behaviors with the Z-letter and offsets. But, again, you should not even be using SimpleDateFormat.
Why: When I give input date string with GMT timezone, SimpleDateFormat parses it and outputs EET timezone?
public static String DATE_FORMAT="dd MMM yyyy hh:mm:ss z";
public static String CURRENT_DATE_STRING ="31 October 2011 11:19:56 GMT";
...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(simpleDateFormat.parseObject(CURRENT_DATE_STRING));
And the output is:
Mon Oct 31 13:19:56 EET 2011
rather than
Mon Oct 31 13:19:56 GMT 2011
You're printing out the result of Date.toString(). A Date doesn't have any concept of a timezone - it's just the number of milliseconds since the UTC Unix epoch. Date.toString() always uses the system default time zone.
Note that you shouldn't be expecting "Mon Oct 31 13:19:56 GMT 2011" given that you've given a time which specifies a GMT hour of 11, not 13.
If you want to use a specific time zone for printing, you should use another DateFormat for the printing, rather than using Date.toString(). (Date.toString() keeps causing confusion like this; it's really unfortunate.)
java.util.Date does not hold timezone information.
A java.util.Date object simply represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone.
Apart from this, there are a couple of problems with your code:
Use H instead of h for the 24-Hour format. The letter, h is used for the 12-Hour format (i.e. with AM/PM marker).
Even though MMM works for parsing the long name of the month (e.g. January) with SimpleDateFormat, it is meant for the 3-letter month name (e.g. Jan). If you try doing it with the modern Date-Time API, you will be greeted with the DateTimeParseException. You should use MMMM for the long name of the month.
Demo incorporating these points:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "31 October 2011 11:19:56 GMT";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy HH:mm:ss z", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(strDateTime);
String strDate = sdf.format(date);
System.out.println(strDate);
// Some other format
sdf = new SimpleDateFormat("MMMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
strDate = sdf.format(date);
System.out.println(strDate);
// The last format with some other timezone
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
strDate = sdf.format(date);
System.out.println(strDate);
}
}
Output:
31 October 2011 11:19:56 GMT
October 31 11:19:56 GMT 2011
October 31 07:19:56 EDT 2011
ONLINE DEMO
Switch to java.time API.
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.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "31 October 2011 11:19:56 GMT";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMMM uuuu HH:mm:ss z", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
// Some other format
DateTimeFormatter dtfAnother = DateTimeFormatter.ofPattern("MMMM dd HH:mm:ss z uuuu", Locale.ENGLISH);
String strDate = dtfAnother.format(zdt);
System.out.println(strDate);
}
}
Output:
2011-10-31T11:19:56Z[GMT]
October 31 11:19:56 GMT 2011
ONLINE DEMO
The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
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.