I need to parse a string to year in the format "yyyy". The code snippet I use is
try{
String strDate = "200323";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
Date dateStr = formatter.parse(strDate);
System.out.println("The year is " + dateStr);
}
catch(Exception e){
System.out.println("Date parse exception");
}
The problem is if I use a string with 4 digits, say "2003", its parsed to the year and the output is as expected "The year is Wed Jan 01 00:00:00 GMT 2003". But when we give an invalid string of more than 4 digits as in the above snippet, say "200323", it does not throw a parse exception, instead it accepts the string value and the output is shown as "The year is Mon Jan 01 00:00:00 GMT 200323". Can anyone suggest a solution to either resolve this or atleast make it throw parse exception? I even tried formatter.setLenient(false) before parsing, but it did not show any effect. Any help is appreciated. Thanks in advance.
You mean that Date range is upto 9999 than you are wrong friend
java date range is
Start: Sat Jan 01 00:00:00 PST 1
End: Wed Apr 17 21:34:08 PST 292269054
so you can't handle that.
Related
This question already has answers here:
What is the use of "lenient "?
(7 answers)
Closed 7 years ago.
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = "35/35/1985";
Date date = sdf.parse(dateStr);
i was expecting run time exception like date parse exception but returned date object is Sat Dec 05 00:00:00 IST 1987
By what logic string 35/35/1985 parsed to date Sat Dec 05 00:00:00 IST 1987?
update:- If I set the setLenient(false), it throws exception. But if I make it true
By what logic string 35/35/1985 parsed to date Sat Dec 05 00:00:00 IST 1987?
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = "35/35/1985";
Date date = sdf.parse(dateStr);
To answer your "logic behind" question: Well, it will be parsed as
xx.xx.1985
-> set / add 35 Months (xx.35.1982 -> xx.11.1987)
-> set / add 35 Days (35.11.1987 -> 05.12.1987)
If you don't want this behaviuor, set lenient to false:
http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient%28boolean%29
To keep track of time, Java counts the number of milliseconds from the start of January 1, 1970. This means, for example, that January 2, 1970, began 86,400,000 milliseconds later. (...) The Java Date class keeps track of those milliseconds as a long value. Because long is a signed number, dates can be expressed before and after the start of January 1, 1970.
From JavaWorld.com
Basically, Java's engine does not know what a Date is, so a date is nothing but a reference to how many milliseconds have passed since the "Beginning" and it will then be converted to a nice MM/DD/YYYY format. Same thing in the other direction. So technically, 35/35/1985 is not a mistake, it simply means "substract 34 months, 34 days and 1985 years to 0 months, 0 days and 1970 years".
This can be useful if you are calculating Loans for example where people tend to reference 5 years as "60 months". See the point?
In you above code
you mentioned
year => 1985
month=> 35
day =>35
now first, year is 1985. if month is 12 then it will be 1985 after that when month is 24 it will be 1986. above 24, year will be 1987 and for month 35 it is Nov 1987. now your date is 35 which is above 30 so it will go to December 5 with adding one year i.e 1987.
so finally Dec 5 1987.
I am probably overlooking something, but parsing from string to date is not working correctly for me.
I have String: "20110705_060229" which is format: "YYYYddMM_HHmmss"
this piece of code:
Date triggermoment;
public void setTriggermoment(String triggermoment) throws ParseException {
DateFormat formatter = new SimpleDateFormat("YYYYddMM_HHmmss");
this.triggermoment = formatter.parse(triggermoment);
}
gives me as output (when I run toString() method on triggermoment):
Mon Jan 03 06:02:29 CET 2011
Why is it not parsing the day's and month's correctly? It should be June 7 instead of Jan 3.
Thanks in advance!
You have to use y for years. Y is used for week year :
DateFormat formatter = new SimpleDateFormat("yyyyddMM_HHmmss");
Output:
Sat May 07 06:02:29 CEST 2011
It should be June 7 instead of Jan 3
The 5th month in the year is may, not june.
MM is month whereas mm is munutes. y is for year and Y is used for Week year.
Try yyyyddMM_HHmmss instead of YYYYddMM_HHmmss
This is the String I'm extracting the info from using a regex:
2823893a2f91c7507831f140dd7aa75e420477b0 - #0023922: Fixed the message
for defaulted bonds ; Thu Oct 25 12:08:25 2012 +0000
This is the code I use to extract the String and then try to make it into a Date:
Pattern pattern3 = Pattern.compile(";\\s(.*)");
Matcher matcher3 = pattern3.matcher(s);
matcher3.find();
String t = matcher3.group(1).toString();
try {
Date time = new SimpleDateFormat("dd/MMM/yy hh:mm a").parse(t);
} catch (ParseException e) {
e.printStackTrace();
}
This should be the format of my input:
Thu Oct 25 12:08:25 2012 +0000
And what I want is to make a Date from the aforementioned string which looks like:
25/Oct/12 12:08 PM
But I keep getting these errors:
java.text.ParseException: Unparseable date: "Thu Oct 25 12:08:25 2012 +0000"
Fixed the message for defaulted bonds0null
at java.text.DateFormat.parse(DateFormat.java:337)
at GitItem.cultivateGitItem(GitItem.java:42)
at main.main(main.java:9)
java.text.ParseException: Unparseable date: "Thu Oct 25 11:52:39 2012 +0000"
at java.text.DateFormat.parse(DateFormat.java:337)
at GitItem.cultivateGitItem(GitItem.java:42)
at main.main(main.java:9)
Your pattern has to match the pattern of the incoming data, which it doesn't right now.
SimpleDataFormat can't read your mind, the pattern you are giving it doesn't match the format you are passing into .parse().
"dd/MMM/yy hh:mm a" will never match Thu Oct 25 12:08:25 2012 +0000, you have to specify the exact pattern that the incoming data is in, this is very well documented in the JavaDocs.
Then you can change the pattern to what you want using .applyPattern() can call .format() to get the formatted output you want.
I would simply remove the unwanted part:
String dateAsString = s.replaceAll(".*;\\s+","");
Then you need to DateFormat: one to parse the string and another one to output the correct format:
String s = "2823893a2f91c7507831f140dd7aa75e420477b0 - #0023922: Fixed the message for defaulted bonds ; Thu Oct 25 12:08:25 2012 +0000";
System.out.println("s = " + s);
String dateAsString = s.replaceAll(".*;\\s+","");
System.out.println("dateAsString = " + dateAsString);
DateFormat parser = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy X", Locale.ENGLISH);
Date date = parser.parse(dateAsString);
System.out.println("date = " + date);
DateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy hh:mm a", Locale.ENGLISH);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(formatter.format(date));
outputs:
s = 2823893a2f91c7507831f140dd7aa75e420477b0 - #0023922: Fixed the message for defaulted bonds ; Thu Oct 25 12:08:25 2012 +0000
dateAsString = Thu Oct 25 12:08:25 2012 +0000
date = Thu Oct 25 14:08:25 CEST 2012
25/Oct/2012 12:08 PM
Note: you need to use the appropriate locale to parse and print the month/day names
I'm sure this is a simple one!
I've got this String String date = "Wed, 2 Jan 2013 12:17:15 +0000 (GMT)" which I want to parse to a Date to be able to set an JavaMail's sent date.
Here's my full code
String dateString = "Wed, 2 Jan 2013 12:17:15 +0000 (GMT)";
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
Date date = sdf.parse(dateString);
System.out.println("Date: " + date.toString());
email.setSentDate(oDate); // Assume email is initialised correctly
Expected output
Date: Wed, 2 Jan 2013 12:17:15 +0000 (GMT)
Actual output
Date: Wed Jan 02 12:17:15 GMT 2013
I'm not even bothered about the time component, as long as my email appears to be from the correct date.
Try this:
String reformattedStr = sdf.format(sdf.parse(dateString));
or this
String reformattedStr = sdf.format(sdf.parse(date.toString()));
Date.toString() applies its own format when converting to string:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
You should use DateFormat to get a desired string, ie for a posted code example:
System.out.println(sdf.format(date));
The setSentDate method will format the date properly for an email message before setting it in the email message. That's different than what Date.toString() does. See also the MailDateFormat class.
I've written a method that returns the milisecond value of a string formatted date, and for some reason it's giving me dates 39000 years in the future. any ideas why?
private long getTimeInMs(String currentStartTimeString) {
//String newDateString = currentStartTimeString.substring(6,10)+"-"+currentStartTimeString.substring(3, 5)+"-"+currentStartTimeString.substring(0, 2)+ "T" + currentStartTimeString.substring(11);
String newDateString = currentStartTimeString.substring(0,19);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timeInMs;
try {
timeInMs = df.parse(newDateString).getTime();
} catch (ParseException e) {
log.error("Failed to parse current Start Time",e);
return 0;
}
return timeInMs;
}
If I enter the date string "2009-07-07 10:51:01.15" it returns 1246960261000 which is actually Wed Aug 06 41484 11:16:40 GMT+0100 (GMT Daylight Time)
Okay I think the issue is that it's giving ms past the Java epoc and I'm evaluating it against the unix epoch...
I'm guessing that you interpreted the returned value from getTime() as if it was a Unix time_t value. It's not - it's milliseconds past the Java epoch, not seconds past the Unix epoch.
It looks fine to me. The Date object that comes out of the parse toString's to "Tue Jul 07 10:51:01 BST 2009" (I'm in the UK timezone here), but that should make no big difference). The millis value of 1246960261000 is correct, why do you think that evaluates to the far future? How did you calculate that?
The value is correct, in fact :
(((((1246989061000 / 1000) / 60)/60)/24)/365)
gives
39.54176373033992 years which is about correct given that 0 is 1970.
running your code in Java 6, i get 1246978261000, which turns out to be correct.
System.out.println(new Date(timeInMs));
returns
Tue Jul 07 10:51:01 EDT 2009
edit:
to confirm others' suggestions that you are looking at seconds (not millis):
System.out.println(new Date(timeInMs*1000));
yields
Mon Mar 02 13:16:40 EST 41485