I am sorry if its a very stupid mistake that i am doing but i cant seem to see it. I am getting an Unparsable date exception while trying to parse 2012-08-28T21:52:57.020Z by using SimpleDateFormat with "yyyy-MM-dd'T'HH:mm:ss.SSSZ" as the format string. Can some one please point me to the problem.
I don't think SimpleDataFormat parses "Z" in the parsed String as a time zone. :( It only tread Z in the format as the place to find the time zone.
Try the format "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" or try JodaTime which has better handling of time zones.
The 'Z' in the end corresponds to the time zone. You should replace that 'Z' in your input with time zone ID like IST/EST etc.,
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String date = "2012-08-28T21:52:57.020IST";
System.out.println(df.parse(date));
output: Tue Aug 28 21:52:57 IST 2012
Related
I want to convert the date in string to date object being the string "10h 57m 20s October 13 2020". How can be done? may replace firstly the h, m and s to get the format "10:57:20 October 13 2020"? As well, I tried the last format "10:57:20 October 13 2020" to get the date with DateTimeFormat and DateTimeFormatterBuilder() but is does not work with the month or it works but the hour coverts to 00:00:00.
Thanks
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. Like Joop Eggen already wrote, put the letters that are part of your format in single quotes in the format pattern string:
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("H'h' m'm' s's' MMMM d y", Locale.ENGLISH);
This will allow you to parse like this:
String dateInString = "10h 57m 20s October 13 2020";
LocalDateTime dateTime = LocalDateTime.parse(dateInString, FORMATTER);
System.out.println(dateTime);
Output:
2020-10-13T10:57:20
You shouldn’t take any interest in the old-fashioned Date class. However, sometimes we need to pass a Date to a legacy API not yet upgraded to java.time. The conversion requires that we know the time zone assumed for the parsed date and time. For example:
ZoneId zone = ZoneId.of("America/Tegucigalpa");
Instant i = dateTime.atZone(zone).toInstant();
Date oldfashionedDate = Date.from(i);
System.out.println(oldfashionedDate);
Example output:
Tue Oct 13 10:57:20 CST 2020
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.
You can place fixed letters in apostrophes.
"HH'h' mm'm' ss's' MMMM dd yyyy"
Furthermore hh is the 12 hour format to be combined wiht a AM/PM.
HH is the 24 hour format.
Also the locale must be correct, maybe explicitly set. Here English.
I am trying to get my current system date and am formatting it into Etc/UTC and then into this "dd.MM.yyyy HH:mm z" format. The problem is this that the format function after formatting the date returns a string instead of date. Here is the code spinet below
final Date currentDate = new Date();
final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm z");
dateFormatter.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String finalDateTime= dateFormatter.format(currentDate);
System.out.println(finalDateTime);
Is there any alternative solution which allows me to format the date by keeping me within this date object because I have researched every date library after java 8 and before java 8, it seems like if I want to format any type of date or dateTime, I have to use a formatter which converts the given date into string.
Any Alternative solutions or it is not possible?
Date represents a single point in time. That's it, nothing more, nothing less. It does not contain any information about time zones.
Wed Jun 06 12:38:15 BST 2018 is the same Date (instant) as Wed Jun 06 11:38:15 GMT 2018, just in a different time zone. It's like the words "humans" and "homo sapians". They refer to the same species, they are just kind of in a different "format".
So you don't need to change the date in any way. You just need to format it differently. This is why formatters return Strings. Only Strings can represent one particular format of a date.
I'm having trouble parsing a date format that I'm getting back from an API and that I have never seen (I believe is a custom format). An example of a date:
/Date(1353447000000+0000)/
When I first encountered this format it didn't take me long to see that it was the time in milliseconds with a time zone offset. I'm having trouble extracting this date using SimpleDateFormat though. Here was my first attempt:
String weirdDate = "/Date(1353447000000+0000)/";
SimpleDateFormat sdf = new SimpleDateFormat("'/Date('SSSSSSSSSSSSSZ')/'");
Date d1 = sdf.parse(weirdDate);
System.out.println(d1.toString());
System.out.println(d1.getTime());
System.out.println();
Date d2 = new Date(Long.parseLong("1353447000000"));
System.out.println(d2.toString());
System.out.println(d2.getTime());
And output:
Tue Jan 06 22:51:41 EST 1970
532301760
Tue Nov 20 16:30:00 EST 2012
1353447000000
The date (and number of milliseconds parsed) is not even close and I haven't been able to figure out why. After some troubleshooting, I discovered that the way I'm trying to use SDF is clearly flawed. Example:
String weirdDate = "1353447000000";
SimpleDateFormat sdf = new SimpleDateFormat("S");
Date d1 = sdf.parse(weirdDate);
System.out.println(d1.toString());
System.out.println(d1.getTime());
And output:
Wed Jan 07 03:51:41 EST 1970
550301760
I can't say I've ever tried to use SDF in this way to just parse a time in milliseconds because I would normally use Long.parseLong() and just pass it straight into new Date(long) (and in fact the solution I have in place right now is just a regular expression and parsing a long). I'm looking for a cleaner solution that I can easily extract this time in milliseconds with the timezone and quickly parse out into a date without the messy manual handling. Anyone have any ideas or that can spot the errors in my logic above? Help is much appreciated.
Take the milliseconds value in the string:
/Date(1353447000000+0000)/
and pass that value as a long into the Date constructor:
Date date = new Date(1353447000000);
and format the date object using SimpleDateFormat.
Even though it's pretty much what you're doing now, I don't think there's much wrong with the manual method - other than it's a shame you have to go there!
I don't believe you can do it solely with SDF.
This will give you a date reasonably 'elegantly':
Date date = new Date(Long.parseLong(weirdDate.split("[^\\d]")[6]));
I'm sure you've already considered it, but have you spoken to the producer of the API to see why they are outputting this value in such an odd format? If the interface is not public and/or not widespread they may consider changing it to something a bit more conventional.
I am facing an issue with parsing/converting a dateString from browser to Date format in Java.
The following are some of the values that I got from the browser.
dateStr = "01-01-2010 05:06:22";
dateStr = "Mon Oct 11 07:00:00 EDT 2010";
dateStr = "Fri May 25 2012 08:00:00 GMT-0400 (Eastern Daylight Time)";
Each dateStr is in different format and at the back-end I was using a SimpleDateFormat with a particular format to convert dateStr. Since the input dateStr format is not consistent, any idea about how this can be handled in the backend?
There is little access to the frontend code/folks.
PS: I did google about this and read the related topics here on StackOverflow.
Any sort of help is greatly appreciated. Thank you.
You have all the pieces you need. First define patterns for every possible date format you can get from the client. Then simply iterate over these formats and try parsing input using each of them and SimpleDateFormat.
Continue looping if SimpleDateFormat returns null (parse error) until you get valid Date. You might ask: what to do if input matches more then one pattern (is 02-01-2012 2nd of January or February the 1st?) Well, then you have bigger issues...
In my app, I am using SimpleDateFormat to convert the Date object to a string. But sometime when I change the time zone one by one to test whether the date I enter is the same as the date converted to a string, I found that it shows a different date. For example, suppose I have Thu Mar 15 00:00:00 GMT+08:00 2012 in my Date object, Now when I convert it to a string using SimpleDateFormat it works fine, but when I change the time zone one by one and check whether the date converted to string is same as it stored in Date object then in some cases it shows as 14-Mar-2012 instead of showing 15-Mar-2012. Why this happen? Can anyone please suggest me how to solve this out?
Code I have used:
SimpleDateFormat m_sdFormatter = new SimpleDateFormat("dd-MMM-yyyy");
String selected_date = m_sdFormatter.format(btnSelectedDt.getTime());
try this ,hope it may help you..
private String getDate(long timeStamp) {
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy");
objFormatter.setTimeZone(TimeZone.getDefault());
Calendar objCalendar = Calendar.getInstance(TimeZone.getDefault());
objCalendar.setTimeInMillis(timeStamp * 1000);
String result = objFormatter.format(objCalendar.getTime());
objCalendar.clear();
return result;
}
For example suppose i have Thu Mar 15 00:00:00 GMT+08:00 2012 in my Date object,
You haven't got that (even though that's no doubt what toString displays). A Date object doesn't contain a time zone. It contains an instant in time, which can be interpreted as different dates and times based on the calendar and time zone you use to interpret it. So that's midnight in once specific time zone - but the Date object itself is just a number of milliseconds since the unix epoch.
It's not clear exactly what you're doing, but you shouldn't be surprised that changing the time zone used in SimpleDateFormat will change the date written out. If you can describe in more detail what the larger goal is, we may be able to help you more. Note that if you can use Joda Time instead, that's a much better date/time API - but I know that it's quite large for use in an Android app.
In your SimpleDateFormat, mention the locale,
DateFormat objFormatter = new SimpleDateFormat("dd-MM-yyyy", locale);
where locale is of your choice. For eg, I use Locale.ENGLISH as it contains the date format that I require. Otherwise when you change ure locale in the device, the simpledateformat changes to current locale and you end up getting the wrong date.