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);
Related
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.
Im working on an RSS reader software. I get items with their pubDate (publish date) values as string, convert them to Date object, and put them to my DB. However, when I check my DB, I saw some interesting values such as the date of tomorrow.
I research this situation and found that it is about time zone value Z. For example when I get "Mon, 26 May 2014 21:24:29 -0500", it becomes "2014-05-27 05:24:29", the next day !
All I want is to get dates in any timezone and convert them to date in common timezone, such as my country's.
Here is my code :
public static String convert(String datestr) throws ParseException {
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Date date = formatter.parse(datestr);
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return resultFormatter.format(date);
}
And I use the method like that :
System.out.println(convert("Mon, 26 May 2014 21:24:29 -0500"));
The output is : 2014-05-27 05:24:29
Any idea ?
Since you haven't set a time zone, it's using your system's default.
Set a specific IANA time zone.
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
resultFormatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
return resultFormatter.format(date);
Looks like you passed a Date with timezone, but given a wrong format. If you are passing timezone like "-0500" you should rather use:
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
Remember that the system will always display the date using the current, default timezone (TimeZone.getDefault()) unless you override it by:
resultFormatter.setTimeZone(...)
This is working as expected. The date is converted as per your system's timezone.
Check the UTC offset of your system and replace it in the sample date string and look at the output.
For e.g: India is UTC+5:30
String datestr="Mon, 26 May 2014 21:24:29 +0530";
output:
2014-05-26 21:24:29
Alternate solution
If you don't want to consider the timezone of the input date string then simply truncate this information and remove zzz from pattern as well as shown in below code:
String datestr = "Mon, 26 May 2014 21:24:29 -0530";
datestr = datestr.replaceAll("\\s[-+](\\d+)$", ""); // truncate the timezone info if not needed
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); // remove zzz from the pattern
Date date = formatter.parse(datestr);
SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(resultFormatter.format(date));
Currently using Parse to obtain a date on an object by using:
Date date = object.getCreatedAt();
The returned String when displaying it in a TextView is this:
Mon Mar 17 22:39:27 CET 2014
However I really only want the MM/DD/YYYY to display like so: 3/17/2014
I've tried this:
Date date = object.getCreatedAt();
SimpleDateFormat originalFormat = new SimpleDateFormat("MMM DDD yyyy");
try {
Date originaldate = originalFormat.parse(date.toString());
finalDate = originaldate.toString();
} catch (java.text.ParseException e1) {
e1.printStackTrace();
}
but keep getting a ParseException for "Unparseable date", any idea what's going on? If I were to simply change this line back to this:
SimpleDateFormat originalFormat = new SimpleDateFormat("EEE MMM DDD HH:mm:ss z yyyy");
Then it prints out the full date again just fine with no parse exception, including all the date stuff I don't want.
Don't use parse method, use format instead :
Date date = object.getCreatedAt();
SimpleDateFormat formater = new SimpleDateFormat("M/d/yyyy");
String datestring = formater.format(date); // value is : 3/17/2014
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()
java.util.Date.toString() method always returns a String of format
dow mon dd hh:mm:ss zzz yyyy
For example, Thu Jan 10 02:00:00 EET 1992.
Your Date format "MMM DDD yyyy" expects a date String like Jan 10 1992 where 10 represents not 10th day of January but 10th day of year 1992.
Therefore to convert a date to String and convert it back to Date object using your format, you need to do
Date originaldate = originalFormat.parse(originalFormat.parse(date.toString()));
Or to convert Date.toString() to Date object,
SimpleDateFormat toStringFormat = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy");
Date originaldate = toStringFormat.parse(date.toString());
Lastly, if you want a Date string with format like 3/17/2014, the correct format is M/d/yyyy.
Refer to http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html for help on how to write Date format.
I'm trying to parse a string to a date, this is what I have:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zZ (zzzz)");
Date date = new Date();
try {
date = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
the string to parse is this:
Sun Jul 15 2012 12:22:00 GMT+0300 (FLE Daylight Time)
I followed the http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Pretty sure I've done everything by the book. But it is giving me ParseException.
java.text.ParseException: Unparseable date:
"Sun Jul 15 2012 12:22:00 GMT+0300 (FLE Daylight Time)"
What am I doing wrong? Patterns I Have tried:
EEE MMM dd yyyy HH:mm:ss zzz
EEE MMM dd yyyy HH:mm:ss zZ (zzzz)
You seem to be mixing the patterns for z and Z. If you ignore the (FLE Daylight Time), since this is the same info as in GMT+0300, the problem becomes that SimpleDateFormat wants either GMT +0300 or GMT+03:00. The last variant can be parsed like this:
String time = "Sun Jul 15 2012 12:22:00 GMT+03:00 (FLE Daylight Time)";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzz");
Date date = sdf.parse(time);
[EDIT]
In light of the other posts about their time strings working, this is probably because your time string contains conflicting information or mixed formats.
java.time
I should like to contribute the modern answer. Use java.time, the modern Java date and time API, for your date and time work.
First define a formatter for parsing:
private static final DateTimeFormatter PARSER = DateTimeFormatter
.ofPattern("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (", Locale.ROOT);
Then parse in this way:
String time = "Sun Jul 15 2012 12:22:00 GMT+0300 (FLE Daylight Time)";
TemporalAccessor parsed = PARSER.parse(time, new ParsePosition(0));
OffsetDateTime dateTime = OffsetDateTime.from(parsed);
System.out.println(dateTime);
Output is:
2012-07-15T12:22+03:00
I am not parsing your entire string, but enough to establish a point in time and an offset from GMT (or UTC). Java cannot parse the time zone name FLE Daylight Time. This is a Microsoft invention that Java does not know. So I parse up to the round bracket before FLE in order to validate this much of the string. To instruct the DateTimeFormatter that it needs not parse the entire string I use the overloaded parse method that takes a ParsePosition as second argument.
From Wikipedia:
Sometimes, due to its use on Microsoft Windows, FLE Standard Time (for
Finland, Lithuania, Estonia, or sometimes Finland, Latvia, Estonia) …
are used to refer to Eastern European Time.
If you indispensably need a Date object, typically for a legacy API that you cannot afford to upgrade to java.time just now, convert like this:
Date oldfashionedDate = Date.from(dateTime.toInstant());
System.out.println(oldfashionedDate);
Output when run in Europe/Tallinn time zone:
Sun Jul 15 12:22:00 EEST 2012
What went wrong in your code?
Your SimpleDateFormat successfully parsed GMT+03 into a “time zone” matching the small z in the format pattern string. It then tried to parse the remaining 00 into an offset to match the capital Z. Since an offset requires a sign, this failed.
What am I doing wrong?
As others have said, you should not try to parse GMT into a time zone abbreviation. GMT can be used as a time zone abbreviation; but your time is not in GMT. So you don’t want that. It would only be misleading. Had you been successful, you would rather have risked an incorrect result because you had parsed a time zone that was incorrect for your purpose.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Eastern European Time on Wikipedia.
Try it this way..
System.out.println(new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zZ (zzzz)").format(new Date()));
Output i got:
Thu Jul 12 2012 12:41:35 IST+0530 (India Standard Time)
You can try to print the date format string :
/**
* #param args
*/
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zZ (zzzz)");
Date date = new Date();
try {
//
System.out.println(sdf.format(date));
date = sdf.parse(time);
} catch (Exception e) {
e.printStackTrace();
}
}
If you have problems with locales, you can either set the default Locale for the whole application
Locale.setDefault(Locale.ENGLISH);
or just use the english locale on your SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zZ (zzzz)", Locale.ENGLISH);
You can also use Locale.US or Locale.UK.
Given the following:
String dt = "Wed Jan 1 12:34:03 2010";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy");
Date output = sdf.parse(dt);
Produces:
Wed Jan 1 12:34:03 ADT 2010
Where is the timezone coming from? I don't have z in my format pattern.
Thanks,
Doug
You're apparently displaying the toString() outcome of the Date object like as
System.out.println(output);
The format is specified in the javadoc and it indeed includes the timezone.
toString
public String toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
You need SimpleDateFormat#format() to convert the obtained Date object to a String in the desired format before representing it. For example,
String s = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(output);
System.out.println(s); // 01-01-2010 12:34:03
When a Date object is created, the timezone is set from the system settings.
try output.getTimeZoneoffset() and it returns the offset in minutes (for ADT it's -180)