Java DateFormat not converting correctly - java

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

Related

getDateTimeInstance customized time format

Using this code:
DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL, new Locale("no")).format(Date);
Date 3 AM CST 12 DEC 16 would have a result of: 12. desember 2016 kl 03.00 CST
But what if I only want to show the hours in the time format and remove the minutes and seconds if ever it was present on other locales?
Expecting a result of 12. desember 2016 kl 03 CST or if using English locale then should only be December 12, 2016 3 AM CST
How about having a SimpleDateFormatter like below:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd. MMMMM yyyy aa hh z", new Locale("no"));
System.out.println(dateFormat.format(new Date()));

Why string '35/35/1985` parses to `Sat Dec 05 00:00:00 IST 1987` date object? [duplicate]

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.

DateFormat giving incorrect value

I wanted to convert String to Date. My code:
String maturityDate = "20150722";
SimpleDateFormat formatter = new SimpleDateFormat("yyyymmdd");
Date date = formatter.parse(maturityDate);
System.out.println(date);
Expected Result :
Input 20150722
Output Wed Jul 22 00:07:00 IST 2015
Actual Result :
Input 20150722
Output Thu Jan 22 00:07:00 IST 2015
What could be the cause?
What could be the cause?
Cause is m letter means minute in SimpleDateFormat pattern. You mean M for months.
SOLUTION
Change your format from yyyymmdd to yyyyMMdd.
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
In the API you will find the complete list:
M Month in year Month July; Jul; 07
m Minute in hour Number 30

Java Date year calculation is off by year for two days

This caused a Y2K-style bug in my software if you can imagine. Strange thing is the off-by-one year calculation only occurs for two days in the year, which I'm less sure how to troubleshoot.
The output:
03-Jan-2013
02-Jan-2013
01-Jan-2013
31-Dec-2013 ** strange
30-Dec-2013 ** strange
29-Dec-2012
28-Dec-2012
27-Dec-2012
26-Dec-2012
25-Dec-2012
I am not sure which part of the Java date utilities could cause such an error.
The code (since the test is so small I included a complete working program):
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
public class DateT {
private static String getFormattedBackscanStartTime(int days) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-YYYY");
Calendar workingDate = Calendar.getInstance();
workingDate.add(Calendar.DATE, -1 * days);
String formattedStartTime = dateFormat.format(workingDate.getTime());
return formattedStartTime;
}
public static void main(String args[]) {
for(int i = 35; i < 45; i++) {
System.out.println(getFormattedBackscanStartTime(i));
}
}
}
This is the problem:
"dd-MMM-YYYY"
YYYY is the week-year, not the calendar year. You want yyyy instead.
The last two days of calendar year 2012 were in the first week of week-year 2013. You should normally only use the week year in conjunction with the "week of year" specifier (w).
I am assuming you are using java 1.7.
The code snippet above will not work with java 1.6 as SimpleDateFormat("dd-MMM-YYYY") will raise an java.lang.IllegalArgumentException (YYYY is not available in java 1.6)
You need to use yyyy instead of YYYY.
Y -> week-year
y -> year
here
EDIT
Works great with yyyy:
$ java DateT
03-Jan-2013
02-Jan-2013
01-Jan-2013
31-Dec-2012
30-Dec-2012
29-Dec-2012
28-Dec-2012
27-Dec-2012
26-Dec-2012
25-Dec-2012
The problem lies in your date format string - year should be yyyy not YYYY.
If you print the value of workingDate.getTime() in each iteration of the loop, you'll see it has the expected values:
Thu Jan 03 11:19:33 EST 2013
Wed Jan 02 11:19:33 EST 2013
Tue Jan 01 11:19:33 EST 2013
Mon Dec 31 11:19:33 EST 2012
Sun Dec 30 11:19:33 EST 2012
Sat Dec 29 11:19:33 EST 2012
Fri Dec 28 11:19:33 EST 2012
Thu Dec 27 11:19:33 EST 2012
Wed Dec 26 11:19:33 EST 2012
Tue Dec 25 11:19:33 EST 2012
Therefore the problem lies in the SimpleDateFormat usage.
For the sake of completeness, here’s the modern answer using LocalDate (as recommended by Basil Bourque in a comment).
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DateT {
private static DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.US);
private static String getFormattedBackscanStartTime(int days) {
return LocalDate.now(ZoneId.systemDefault()).minusDays(days).format(dateFormatter);
}
public static void main(String args[]) {
for(int i = 155; i < 165; i++) {
System.out.println(getFormattedBackscanStartTime(i));
}
}
}
Running this today I got
04-Jan-2017
03-Jan-2017
02-Jan-2017
01-Jan-2017
31-Dec-2016
30-Dec-2016
29-Dec-2016
28-Dec-2016
27-Dec-2016
26-Dec-2016
A few things to note:
Give an explicit locale to your formatter to control the langauge of your output. Even if you just pass Locale.getDefault() you are telling the reader that you have thought about locale and made a decision.
Similarly give an explicit time zone to LocalDate.now() to tell the reader you’ve made a decision (for example ZoneId.of("America/New_York") for a specific time zone; ZoneId.systemDefault() for the JVM’s current time zone setting).
I find the code simpler and more straightforward than the code using the oldfashioned Calendar class. This is typical for the newer classes.
I have used uuuu for year. yyyy (lowercase) works too, there will only be a difference for years before the common era (AKA BC).
You need to use lower case y for the year. Try this:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");

Parse a string to date of the form "yyyy"

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.

Categories

Resources