Does anyone know how to parse a date such as: Mon Aug 04 16:07:00 CEST 2014
to dd/MM/YYYY HH:MM:SS using DateTime formatter from Joda.
I've tried that:
final DateTimeFormatter sdf = DateTimeFormat.forPattern(DATE_FORMAT);
DateTime lastDateOnline = sdf.parseDateTime(lastCommunicationToDisplay.getDateOnLine().toString());
return lastDateOnline.toString();
DATE_FORMAT = dd/MM/YYYY HH:MM:SS and
lastCommunicationToDisplay.getDateOnLine().toString() = Mon Aug 04 16:07:00 CEST 2014
I can't find clear explanations about that library. I'm requested to use that instead of SimpleDateFormat because it's not threadsafe.
Solutions
If all you have to do is convert a LocalDate to a string respecting the pattern: "dd/MM/YYYY HH:mm:ss", then you can do it in a simpler way, using the overloaded toString() methods on LocalDate:
a) the one which receives the format string directly:
LocalDate date = lastCommunicationToDisplay.getDateOnLine();
System.out.println(date.toString("dd/MM/YYYY HH:mm:ss"));
b) the one which receives a DateTimeFormatter initialized with the aforementioned string:
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm:ss");
LocalDate date = lastCommunicationToDisplay.getDateOnLine();
System.out.println(date.toString(dtf));
What went wrong in your code
The format string you are using is not compatible with the date string you are sending as input. The way you used DateTimeFormatter is used for parsing strings that are in that format to LocalDates, not the other way around.
The format would be appropriate if your input string would look like the following:
04/08/2014 22:44:33
Since yours looks differently, the following value of the format is compatible (provided your timezone is always CEST):
DATE_FORMAT = "E MMM dd HH:mm:ss 'CEST' YYYY";
So the entire code should look like this:
String dateString = "Mon Aug 04 16:07:00 CEST 2014";
DateTimeFormatter dtf = DateTimeFormat.forPattern("E MMM dd HH:mm:ss 'CEST' YYYY");
LocalDate date = dtf.parseLocalDate(dateString);
System.out.println(date.toString("MM/dd/yyyy")); // or use toString(DateTimeFormatter) and use your pattern with a small adjusment here (dd/MM/YYYY HH:mm:ss)
However, I recommend one of the first 2 suggestions.
Related
I am trying to parse this (and many similar) dateString - "Wed Aug 26 2020 11:03:30 GMT-0500"
Looking at the SimpleDateFormat documentation, I was assuming that a pattern like this should work:
String dateFormat = "EEE MMM d yyyy HH:mm:ss z";
However, it doesn't. But the following format is able to parse
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'z";
But when I print the parsed date, I get the time with an hour added and offset reduced by an hour - Wed Aug 26 12:03:30 GMT-04:00 2020
What can I do to prevent this offset change?
Here is the sample code:
String dateStr = "Wed Aug 26 2020 11:03:30 GMT-0500";
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'z";
Date date = new SimpleDateFormat(dateFormat).parse(dateStr);
System.out.println("Original Date String : "+dateStr);
System.out.println("Original Date Object : "+date);
Output:
Original Date String : Wed Aug 26 2020 11:03:30 GMT-0500
Original Date Object : Wed Aug 26 12:03:30 GMT-04:00 2020
Use java.time.OffsetDateTime here because there is no zone in that String, just an offset and the classes you are using are outdated for good reasons... Get rid of java.util.Date and java.text.SimpleDateFormat.
See this example:
public static void main(String[] args) {
// provide the String to be parsed
String dateStr = "Wed Aug 26 2020 11:03:30 GMT-0500";
// provide a matching pattern
String dateFormat = "EEE MMM d yyyy HH:mm:ss 'GMT'Z";
// create a formatter with this pattern and a suitable locale for unit names
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat, Locale.ENGLISH);
// parse the String to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dateStr, dtf);
// print the result in the default format
System.out.println("Default/ISO format:\t" + odt);
// and print it in your custom format
System.out.println("Custom format:\t\t" + odt.format(dtf));
}
Output:
Default/ISO format: 2020-08-26T11:03:30-05:00
Custom format: Wed Aug 26 2020 11:03:30 GMT-0500
While parsing String "Sat Mar 2 09:40:20 PST 2019", it is getting converted to IST. How can I preserve the timezone while parsing the string to a date.
This could be done using standard Java time library and ZonedDateTime class. Take a look at following example how to do it:
String date = "Sat Mar 2 09:40:20 PST 2019";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss zzz yyyy", Locale.ENGLISH);
ZonedDateTime zonedDateTime = ZonedDateTime.parse(date,formatter);
System.out.println(zonedDateTime);
Create a Key/Value pair of all global timezones and their GMT offset, then you can reconvert the times from there. Here's a list: https://publib.boulder.ibm.com/tividd/td/TWS/SC32-1274-02/en_US/HTML/SRF_mst273.htm
This question already has answers here:
String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate]
(5 answers)
Closed 4 years ago.
I have a date object that returns the below string value in doing date.toString()
String date = "Wed Jun 27 12:33:00 CDT 2018";
And I want to format it in exactly this style:
"June-27-2018 5:33:00 PM GMT".
I tried using SimpleDateFormat
protected SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM-dd-yyyy h:mm:ss a z", Locale.US);
But I keep getting a parse exception. Is there any way to format this the way I need it to? The timezone needs to be converted too.
First, you shouldn’t have a Date object. The Date class is long outdated (no pun intended). Today you should prefer to use java.time, the modern and much nicer date and time API. However, I am assuming that you are getting a Date from some legacy API that you cannot change. The first thing you should do is convert it to an Instant. Instant is the corresponding class in java.time. Then you should do any further operations from there.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MMMM-dd-yyyy h:mm:ss a z", Locale.US);
ZoneId desireedZone = ZoneId.of("Etc/GMT");
Date yourOldfashionedDate = // …;
ZonedDateTime dateTimeInGmt = yourOldfashionedDate.toInstant().atZone(desireedZone);
String formattedDateTime = dateTimeInGmt.format(formatter);
System.out.println(formattedDateTime);
This snippet prints the desired:
June-27-2018 5:33:00 PM GMT
Converting directly from the Date object is safer and easier than converting from its string representation. The biggest problem with the latter is that the string contains CDT as time zone, which is ambiguous. It may stand for Australian Central Daylight Time, North American Central Daylight Time, Cuba Daylight Time or Chatham Daylight Time. You cannot be sure which one Java is giving you. Never rely on three and four letter time zone abbreviations if there is any way you can avoid it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Your date string cannot parse to the format you have given, so change the format to EEE MMM dd HH:mm:ss zzz yyyy
String myDate = "Wed Jun 27 12:33:00 CDT 2018";
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
SimpleDateFormat dateFormat_2 = new SimpleDateFormat("MMMM-dd-yyyy h:mm:ss a z", Locale.US);
dateFormat_2.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = dateFormat.parse(myDate);
dateFormat_2.format(d);
System.out.println(dateFormat_2.format(d));
Output :
June-27-2018 12:33:00 PM GMT
You will achieve your desired output if you pass date or object to format function.
SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM-dd-yyyy h:mm:ss a z", Locale.US);
String ans=dateFormat.format(param);
In above code param must be date or object so first convert string to date and then apply format function to get your desired output.
See below Sample code
SimpleDateFormat dateFormat = new SimpleDateFormat( "MMMM-dd-yyyy h:mm:ss a z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String ans=dateFormat.format(new Date());
Sample output:
June-27-2018 6:22:35 PM GMT
I've a problem to convert a data in Java using Joda-Time library.
Pratically, the input date have this format:
Mon Apr 28 18:57:42 CEST 2014
I would like to see this output:
2014-04-28
I've tried this code, but doesn't works:
DateTimeFormatter dtf_out = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTimeFormatter dtf_inp = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss zzz yyyy");
String a = String.valueOf(dtf_inp.parseDateTime(String.valueOf(resultsJs.get(0).getTimestamp()))); //crash here
String b = String.valueOf(dtf_out.parseDateTime(a));
Note: resultsJs.get(0).getTimestamp() is a Date format.
Instead, this is the log:
...
Caused by: java.lang.IllegalArgumentException: Invalid format: "Mon Apr 28 18:57:42 CEST 2014"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:873)
...
You are trying to parse an epoch millisecond value, but you can only parse a String.
However, it seems you already have a millisecond value available, so only the formatting is required, which is via the print() method:
DateTimeFormatter dtf_out = DateTimeFormat.forPattern("yyyy-MM-dd");
String b = dtf_out.print(resultsJs.get(0).getTimestamp().getTime());
Its working fine after removing timezone info from the actual string but I have used time zone while parsing hence it will give you the correct result based on locale.
Please validate the result.
// pattern zzz is removed that is used for parsing time zone
DateTimeFormatter dtf_inp = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss yyyy");
// time zone is added while parsing date time
DateTime dateTime = dtf_inp.withZone(DateTimeZone.forID("Europe/Paris"))
.parseDateTime("Mon Apr 28 18:57:42 2014");
// simply call toString(pattern) on DateTime
System.out.println(dateTime.toString("yyyy-MM-dd")); // 2014-04-28
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String output = sdf.format(yourDate);
I want to convert a string to date before storing it and I used
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
Date returnDate = format.parse(date);
When I ran this with sample date:
the input string for date conversion is 2014-05-06
the parsed date is Mon Jan 06 00:05:00 IST 2014
now when I store the returnDate in MySql the value is 2014-01-06 00:05:00
Why is the date changed ? Want to know if I am missing something. I went through the posts related to date string conversion : How to convert a date from a Datepicker to Mysql DATETIME format using java?
In your DateFormat use MM for month instead of mm, that is for minutes
Reference: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
You can use like this :
Date mDate= new Date(System.currentTimeMillis());
SimpleDateFormat mDateFormat= new SimpleDateFormat("dd MMM yyyy HH:mm a");
String dateformat=mDateFormat.format(mDate);
the string ["dd MMM yyyy HH:mm a"] can be changed according to need of formate.
Like in your case : "yyyy-mm-dd