java.sql.Date is taking wrong date [duplicate] - java

This question already has answers here:
java.util.Date to java.sql.Date conversion gives wrong month
(2 answers)
Closed 8 years ago.
I am using below code,
private static Date date = new Date (2014-1900,11,25);
System.out.println(date);
It is displaying 2014-12-25. I am unable to understand why it is giving me date as 12?
and if i give
private static Date date = new Date (2014-1900,12,25);
it is returning 2015-01-25.
Can anyone help in comprehend this?

Calendar
It accept December month as 11 because month starts from 0 - 11

First you should not use this Constructor, because it is deprecated.
Second: See the documentation of this consturctor:
Parameters:year -
the year minus 1900.month - the month between 0-11.date - the day of
the month between 1-31.See Also:Calendar
month is a null based value, so 0 --> Jan ... 11 --> Dec

from java docs,
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Month's range from 0-11, ie Jan - Dec

Avoid using the depriciated Date() constructor for setting dates, It is recommended to use Calendar class
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
calendar.set(Calendar.DAY_OF_MONTH, 25);
Date date = calendar.getTime();
You can also use the simpleDateFormat for setting/formatting date values:-
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse("25-11-2014");

Related

Setting the year in Calendar [duplicate]

This question already has answers here:
java.util.Date is generating a wrong date?
(3 answers)
Closed 6 years ago.
I have the following piece of code.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/YYYY HH:mm");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DAY_OF_MONTH, 31);
cal.set(Calendar.HOUR_OF_DAY, 22);
Date start = cal.getTime();
System.out.println(dateFormat.format(start));
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 5);
Date end = cal.getTime();
System.out.println(dateFormat.format(end));
It prints:
31/12/2016 22:00
01/01/2016 05:00
I expect that the year of the second date is 2017. What is going on? I'm using Java 1.7.
The correct date format should be dd/MM/yyyy HH:mm, not dd/MM/YYYY HH:mm, note the lower case y.
With that it works correctly.
From the docs:
y Year
Y Week year
Explanation of the difference between year and week year (from here):
A week year is a year where all the weeks in the year are whole weeks.
[...] Basically, this guarantees that a program working on a week's
data will not transition between years. [...] this also means that the beginning of the year may not start on the first of January.
This is working fine with the following dataFormat.
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm");

Creating a new date in Java using ints

I am currently using a Date Picker, to display/select a date. I am just having trouble with the format. below is how the example constructed it.
new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" ").toString();
I don't want this format so I tried the following but it keeps giving the incorrect year even if the values are correct so I am not sure what I am doing wrong.
SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM yyyy");
Date date = new Date(year,month,day);
dates.setText(dateFormat.format(date));
for example if the date was 6 November 2015(current date) and I change it to 6 December 2015 it will display 6 December 3915
The following values are being returned year = 2015 month = 11 day = 6
And this Creates 6 December 3915 I don't understand why the year is not displaying properly if I choose 2016 it would be 3916
This behaviour can be expected actually. This is what the documentation says about the Date constructor you are using (emphasis added by me):
public Date(int year, int month, int day)
Deprecated. instead use the constructor Date(long date)
Constructs a Date object initialized with the given year, month, and day.
The result is undefined if a given argument is out of bounds.
Parameters:
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
month - 0 to 11
day - 1 to 31
So you get 3915 because 2015 + 1900 = 3915
I recommend you don't use this constructor. First of all it is marked as deprecated. Most importantly, no person in his right mind would see an argument int year in a method and think "Of course I have to subtract 1900 from the value I pass"
The LocalDate introduced in Java 8 is recommended as a replacement. You would use it like this
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd MMMM yyyy");
LocalDate date = LocalDate.of(2015, Month.NOVEMBER, 6);
dates.setText(dateFormat.format(date));
the format you are using is wrong. try this instead:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM YYYY");

Date Class error in java

I have Date today=new Date(); which returns the current date.. but when i try to display date,month,year separately with the help of
DateFormat mmFormat=new SimpleDateFormat("MM");
System.out.println(mmFormat.format(today.getMonth()));
DateFormat yyFormat=new SimpleDateFormat("yyyy");
System.out.println(yyFormat.format(today.getYear()));
it prints month as 01 and year as 1970
how to resolve this.?
mmFormat.format(today.getMonth())
You're passing an integer – the month of the date – to a date format method.
The format method interprets that integer as a UNIX timestamp – a number of seconds since 1970.
You need to pass the date itself to the formatter.
Pass the entire date to SimpleDateFormat. The format string "MM" or "yyyy" will cause it to just extract the part of the date you want.
Just use the Date today as the input argument
System.out.println(mmFormat.format(today));
and
System.out.println(yyFormat.format(today));
today.getMonth() and today.getYear() returns an int which is interpreted as an UNIX timestamp . The value is 1 and 113 , which corresponds to approximately January 1, 1970, 00:00:01 GMT and January 1, 1970, 00:01:53 GMT represented by this Date object. To get the desired result , you need to pass the Date object :
System.out.println(mmFormat.format(today));
You would need to use Calendar. Have a look at the java docs.
You can do it like this -
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH)); // month in the Calendar class begins from 0
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
This would help you to avoid creating multiple DateFormat objects. Also in case you want to use another date instead of today's date the you can just pass the date to the cal.setTime() method.
That is because all these methods are deprecated. Use
Calendar myCalendar = GregorianCalendar.getInstance();
myCalendar.get(Calendar.MONTH);
myCalendar.get(Calendar.YEAR);
myCalendar.get(Calendar.DAY_OF_MONTH);
Better in this way
Date date=new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"\n"+month);

Converting Date to Calendar issues

Today is 2013-02-25, but why this code returns 2013-03-25?
String currentDate = new SimpleDateFormat("yyyy MM dd hh mm ss").format(new java.util.Date());
System.out.println("current Date "+currentDate);
StringTokenizer token = new StringTokenizer(currentDate);
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()));
String calenderDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
System.out.println("calender date "+calenderDate);
cal.add(Calendar.MONTH, -1); // set to one month ago
String pastDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
System.out.println("past Date "+pastDate);
out put
current Date 2013 02 25 04 56 26
calender date 2013-03-25 04:56:26
past Date 2013-02-25 04:56:26
Subtract one to the month. So it works the API. I.e.:
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
In the JDK, month values start with 0. So 2 = March.
From the Calendar#set docs:
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
Calendar months start at 0, see JavaDoc:
#param month the value used to set the MONTH calendar field.
* Month value is 0-based. e.g., 0 for January.
This is a royal PITA and most Java developers lost some time on that one, it certainly violates the principle of least surprise. Be very careful when using the Calendar class... There are alternatives like Joda time.

How to compare dates using Java [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 6 years ago.
I have a date with the format 2012-02-02(yyyy-MM-dd).
For example if todays date is 2012-02-02 i need to add one and a half days to it which would make it 2012-02-03 06:00:00.0.
And if i have a number of dates of the following format 2012-02-03 06:30:00.0(yyyy-MM-dd HH:MM:SS.SSS) , i need to compare if all these dates are less than,greater than or equal to the date to which one and a half days were added above.
The comparison should also take care of the hours while comparing if the dates are less than,greater than or equal or equal to the other date and time.
How do i achieve the same.
Simple arithmetic approach (faster)
Parse the date using SimpleDateFormat that creates a Date object
Use Date.getTime() to return the UTC value in long
Convert 1 and half days to millis (1.5 Days = 129600000 Milliseconds) and add it to previous step
Use >, < and == or after(), before() and equals() if you want to use Date object itself
API approach (slower)
Use Calendar
add(...) method for adding 1 and half day
use before(), after() and equals() methods of Calendar
well so i hope this will give you a clear idea. Calendar Documentation and SimpleDateFormat Documentaion
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String aDateString = "2012-02-02";
Date date = sdf.parse(aDateString);
System.out.println("reference date:"+date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 36);
System.out.println("added one and half days to reference date: "+cal.getTime());
String newDateString = "2012-02-03 06:30:00.0";
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date newDate = sdf.parse(newDateString);
System.out.println("new date to compare with reference date : "+newDate);
Calendar newCal = Calendar.getInstance();
newCal.setTime(newDate);
if(cal.after(newCal)){
System.out.println("date is greater than reference that.");
}else if(cal.before(newCal)){
System.out.println("date is lesser than reference that.");
}else{
System.out.println("date is equal to reference that.");
}
OUTPUT :
reference date:Thu Feb 02 00:00:00 IST 2012
added one and half days to reference date: Fri Feb 03 12:00:00 IST 2012
new date to compare with reference date : Fri Feb 03 06:30:00 IST 2012
date is greater than reference that.
Use SimpleDateFormat to convert String to Date
Set date to Calendar instance
use calendar.add(Calendar.HOUR, 36)
Also See
Joda Time API
You need to use Joda date time API.
String strDate="2012-02-02";
DateTime dateTime=DateTime.parse(strDate);
DateTime newDateTime=dateTime.plusHours(18);
System.out.println(dateTime);
System.out.println(newDateTime);

Categories

Resources