java.util.Date is generating a wrong date? - java

Here's my code:
java.util.Date TODAY = new java.util.Date();
SimpleDateFormat SDF = new SimpleDateFormat( "YYYY-MM-DD" );
System.out.println ( SDF.format( TODAY ) );'
And the result is:
2015-02-33
But today's date is 2015-02-02!
What may be the reason behind this wrong output?

You want to use the yyyy year and dd day of the month.
However, I suggest you migrate to JSR-310 which is built into Java 8 and available for earlier versions of Java. The same code is
System.out.println(LocalDate.now());
prints
2105-02-02

What may be the reason behind this Wrong Output ?
Your assumptions about the date format string are wrong, the output is correct.
y Year
Y Week year
D Day in year
d Day in month
M Month in year
m Minute in hour
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Y Week year will usually give incorrect results around new year. D will give incorrect results from February. So your format appeared fine most of last month.

When format for SimpleDateFormat is specified as follows:
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
the YYYY - means week year,
the MM - means month,
the DD - means day in year.
Week year here is not what you wanted. See what is week year.
Your today's date is 2015-02-02, which means that it is 32 days since the beginning of the year 2015 passed and your are on the 33 day. That is why you get date "2015-02-33".
To mean year (and not week year) and day in month change format to SimpleDateFormat("yyyy-MM-dd");

Related

Android DatePickerDialog creates random wrong month [duplicate]

The following code is giving me the parsed date as "Wed Jan 13 00:00:00 EST 2010"
instead of "Wed Jun 13 00:00:00 EST 2010". Any ideas much appreciated.
SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss");
String str = "2010-06-13T00:00:00";
Date date = sf.parse(str);
System.out.println(" Date " + date.toString());
Try:
"yyyy-MM-dd'T'HH:mm:ss"
MM means month. mm means minutes. See the documentation for SimpleDateFormat for more details of the supported date and time patterns.
The problem is that you're using 'mm' as month and 'mm' represents minutes.
Below is all date formats available, read more doc here.
Symbol Meaning Kind Example
D day in year Number 189
E day of week Text E/EE/EEE:Tue, EEEE:Tuesday, EEEEE:T
F day of week in month Number 2 (2nd Wed in July)
G era designator Text AD
H hour in day (0-23) Number 0
K hour in am/pm (0-11) Number 0
L stand-alone month Text L:1 LL:01 LLL:Jan LLLL:January LLLLL:J
M month in year Text M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
S fractional seconds Number 978
W week in month Number 2
Z time zone (RFC 822) Time Zone Z/ZZ/ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00
a am/pm marker Text PM
c stand-alone day of week Text c/cc/ccc:Tue, cccc:Tuesday, ccccc:T
d day in month Number 10
h hour in am/pm (1-12) Number 12
k hour in day (1-24) Number 24
m minute in hour Number 30
s second in minute Number 55
w week in year Number 27
G era designator Text AD
y year Number yy:10 y/yyy/yyyy:2010
z time zone Time Zone z/zz/zzz:PST zzzz:Pacific Standard
Modern answer:
String str = "2010-06-13T00:00:00";
LocalDateTime dateTime = LocalDateTime.parse(str);
System.out.println("Date-time " + dateTime);
Output:
Date-time 2010-06-13T00:00
I am using and recommending java.time, the modern Java date and time API. We don’t even need an explicit formatter for parsing. This is because your string is in ISO 8601 format, the international standard that the java.time classes parse as their default. java.time came out in 2014.
While in 2010 when this question was asked, SimpleDateFormat was what we had for parsing dates and times, that class is now considered long outdated, fortunately, because it was also troublesome.
In case your string contained only a date without time of day, use the LocalDate class in quite the same manner (this was asked in a duplicate question).
String dateStr = "2018-05-23";
LocalDate date2 = LocalDate.parse(dateStr);
System.out.println(date2);
2018-05-23
Link: Oracle tutorial: Date Time explaining how to use java.time.
Example if Date is 06 07 2016
SimpleDateFormat sdf= new SimpleDateFormat("dd MM yyyy");
you can use comma, full-stop, slash, or hyphen between these format.
Ex: dd-mm-yyyy, it will display like(06-07-2016)
dd/mm/yyyy,it will display like(06/07/2016)
dd.mm.yyyy,it will display like(06.07.2016)
dd,mm,yyyy ,it will display like(06,07,2016)
MM - will display number of the Month.
MMM - will display Month Three character only(Ex: Jul)
MMMM - will display full month(Ex: July)
yyyy - will display full year(2016)
yy - will display last two digits(16)
hh - will display hours
mm -will display minutes
ss - will display seconds
a - will display AM or PM
Ex: if time is 12:09:10 PM means (hh:mm:ss a)
EEE- will display short week name(Ex: Wed)
EEEE- will display full week name(Ex: Wednesday)

Confusing Java week format for "20151227" [duplicate]

Can anyone explain why do I get those values while trying to parse a date?
I've tried three different inputs, as follows:
1) Third week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("02.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
Which outputs: 02.2013 (as I expected)
2) First week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("00.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
Which outputs: 52.2012 (which is fine for me, since the first week of 2013 is also the last one of 2012)
3) Second week of 2013
Date date = new SimpleDateFormat("ww.yyyy").parse("01.2013");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + "." + cal.get(Calendar.YEAR));
Which outputs: 1.2012 (which makes absolutely no sense to me)
Does anyone know why this happens?? I need to parse a date in the format (week of year).(year). Am I using the wrong pattern?
You're using ww, which is "week of week-year", but then yyyy which is "calendar year" rather than "week year". Setting the week-of-week-year and then setting the calendar year is a recipe for problems, because they're just separate numbering systems, effectively.
You should be using YYYY in your format string to specify the week-year... although unfortunately it looks like you can't then get the value in a sane way. (I'd expect a Calendar.WEEKYEAR constant, but there is no such thing.)
Also, week-of-year values start at 1, not 0... and no week is in two week-years; it's either the first week of 2013 or it's the last week of 2012... it's not both.
I would personally avoid using week-years and weeks if you possibly can - they can be very confusing, particularly when a date in one calendar year is in a different week year.
Use Calendar.getWeekYear() to get year value synced with Calendar.WEEK_OF_YEAR field.
There is more information about Week of Year and Week Year at the GregorianCalendar doc.

How can we check if the current system date is of 1 Month Back [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to subtract 45 days from from the current sysdate
Hi I am getting the current system date by using
Java.util.Date date = new java.util.Date();
How can i check whether my Date is One month Before date
For example if today is May 22 2011
How can i check if the date is of April 22 2011 ??
You could use JodaTime. Its DateTime class has a minusMonth-method. Use this to get the date from one month ago and then compare. See the Joda-API for more details.
Calendar cal1 = Calendar.getInstance();
cal1.setTime(theGivenDate);
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.MONTH, -1);
if ( (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) &&
(cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) &&
(cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH)) ) {
System.out.println("Given date "
+ theGivenDate + " is exactly one month ago from today");
}
You can use Joda DateTime [http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html] for this.
DateTime has a method minusMonths(int months), and then you can convert Joda DateTime to java.util.Date
Are you aware that many dates will never be "one month before today" according to your definition for month as "calendar month"? For example, since June has only 30 days, the condition will never be true for May 31st.
You may want to change your definition to that commonly used by banks for purposes like calculating interest and deposit terms: a month is considered to be exactly 30 days, independent of calendar dates. So "one month after" May 31st would be June 30th.

SimpleDateParser produces incorrect date?

Good morning! I've been working with the following bit of code for the last two hours, scouring forums, Google and the JDK 1.6 docs for any idea what is going on but can't seem to make this work. I would expect the code to output 07/25/2010 11:59:33 PM but what I get instead is 01/25/2010 11:59:33 PM .
String dateString = "07/25/2010 11:59:33 PM";
DateFormat format = new SimpleDateFormat("MM/DD/yyyy hh:mm:ss a");
Date testDate = format.parse( dateString );
System.out.println(format.format(testDate));
Thinking that it may be something to do with the JDK, I tried writing the same thing using Joda-Time and get the same results. Am I missing something with how DateFormat works?
Thanks in advance for any insight you can provide!
The problem is the "DD" in your format string - it should be "dd".
"DD" means "day of year"... so you're talking about the 25th day of the year, but in the month of July... the "day of year" is taking priority, so you're getting January 25th instead.
DD means day in year as in a Julian day. A Julian day can describe any day in the year, so the month is ignored. Use dd instead (day in month) and you'll get the right result.
U have to take care on case sensitive issues for the formatter. They are a bit weird organised.
Try it with
DateFormat format = new SimpleDateFormat("MM/DD/yyyy hh:mm:ss a");
EDIT: DD means Day in year, dd = day in month
Refering to the JAVA 1.6 API SimpleDateFormat

Difference in Days between two Java dates?

I want to get the difference between two Java Date objects. I've used Joda-Time library. But the problem is that I'm getting the Days greater difference than that of actual day difference.
Here's my code snippet:
DateFormat formatter = new SimpleDateFormat("mm/dd/yyyy");
Date someDate=new Date();
Date today = Calendar.getInstance().getTime();
try {
someDate = formatter.parse("06/22/2010");
}
catch(ParseException pe) {
System.out.println("Parser Exception");
}
int days = Days.daysBetween(new DateTime(someDate), new DateTime(today)).getDays();
System.out.println(" Days Between " + someDate + " : " + today + " - " + days);
Here's my output:
Days Between Fri Jan 22 00:06:00 IST 2010 : Sun Jul 25 19:27:01 IST 2010 - 184
Here, Why does it takes "06/22/2010" as Jan 22? Does anyone face similar problem?
Help me friends.. Thanx in advance..
It seems like mm refers to minutes, not months, which is MM. Please check here to see the list of appropriate lettering :)
Month is MM
In your case:
DateFormat formatter = new
SimpleDateFormat("MM/dd/yyyy");
Your pattern is slightly defective. mm is parsed as minutes in hour, you're looking for MM which is month of year.
mm => minutes, not months - you need MM for months - that'll resolve your Jan problem!
The other answers correctly solved your specific problem.
LocalDate
But there is a larger solution. If you are starting with only dates, no time-of-day and no time zones, then you should be using the LocalDate class rather than DateTime.
Time Zone
Your code ignores the crucial issue of time zones. Time zones matter even for LocalDate, when trying to determine "today". Do you want today's date in Montréal or in Paris. A new day dawns in Paris earlier. When you omit time zone, you get the JVM’s current default time zone.
Joda-Time Can Parse
Furthermore, let Joda-Time do the parsing. No need to be using java.util.Date & .Calendar at all. Joda-time's formatting characters are almost the same as java.util.Date but not entirely so be sire to consult the doc. In this case it it identical.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate past = formatter.parseLocalDate( "06/22/2010" );
DateTimeZone = DateTimeZone.forID( "America/Montreal" ): // match time zone intended for that input string.
int days = Days.daysBetween( past, LocalDate.now( timeZone ) );

Categories

Resources