Error while constructing date - java

I have such code:
Log.d(TAG, "day=%d, month=%d, year=%s", day, month, year);
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
Log.i(TAG, "Date is parsed to %tF", c.getTime(), c.get(Calendar.DAY_OF_MONTH));
And this is log I get when executing:
day=11, month=11, year=1985
Date is parsed to 1985-12-10
Why not 1985-12-11? It works correct for some dates or in debug mode. But why it is not always working?
I also have similar issues when working with Date and when parsing dates from String via SimpleDateFormat
EDIT: Other examples of this code executing:
day=1, month=0, year=2012
Date is parsed to 2012-01-01
day=25, month=11, year=2011
Date is parsed to 2011-12-25
day=4, month=10, year=1979
Date is parsed to 1979-11-03
day=3, month=11, year=1984
Date is parsed to 1984-12-02
day, month and year can't be changed from other threads.

The month in Calendar is zero based. See here: http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#MONTH
I suggest you read this: http://mindprod.com/jgloss/gregoriancalendar.html
If you can, it's actually easier and less bug prone to use joda-time - it has a much neater and safer API.

Month is 0-11 and day starts with 1.
Month
http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#MONTH
Day
http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#DAY_OF_MONTH
Edit:
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1985);
c.set(Calendar.MONTH, 11);
c.set(Calendar.DAY_OF_MONTH, 11);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(c.getTime());
System.out.println(strdate);
Output:
12/11/1985

Try this:
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("MM-dd-yyyy");
Log.v("the date is:", simepleDateFormat.format(c.getTime());

Thanks for the help. It seems to be some Android devices issue. It has appeared in 3 of 5 devices. I have fixed it by specifying time.
c.set(Calendar.HOUR_OF_DAY, 12);
c.set(Calendar.MINUTE, 30);

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");

Convert SAS date value to Java YYYY-MM-DD

I have SAS date objects stored as integer and they look like : 19725.
I am trying to write java code to convert the date to YYYY-MM-DD
I see in the documentation that the SAS date value is the number of days from 01 Jan 1960
For example:
02 Jan 1960 would return 1
04 June 2003 would return 15680
Could you give the java code for this conversion. ie. convert something like 19725 to the date format : YYYY-MM-DD
I try the logic below but 15680 gives 2003-01-06 and not 2003-06-04 as the output. Could anyone point the mistake.Thanks in advance.
int numdays = 15680;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 1960);
cal.add(Calendar.DAY_OF_MONTH, numdays);
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Month are 0-based, so you're setting your calendar to February, not January. This should fix the issue:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.JANUARY);
// ...
In addition to RC's point about starting the month correctly with Calendar.JANUARY, your simpledateformat is wrong.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
'DD' is day of year (so 340th day of the year is Dec 6). 'dd' is day of the month. See the doc for more detail. (Also note that 15680 is Dec 6 2002, not what you say in the question.)
You may actually want to use 'yy' also:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
as 'YYYY' is "Week Year", which in some cases may differ from yyyy (calendar year) near the end of the year. See the docs for more details.
I like to use JodaTime for date manipulation like this.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusDays-int-
int sasDate = 19725;
DateTime base = new DateTime(1960, 1, 1, 0, 0);
DateTime computed = base.plusDays(sasDate);

Changing the date

Basically, I've got a little program that uses date.
Date current = new Date();
current.setDate(current.getDay() + time1);
When I do this it adds to the day, but say time1 = 30 then the month doesn't change when I print the date out. I hope this makes sense I'm kinda new to this.
Use a Calendar to perform date arithmetic and a DateFormat to display the result. Something like,
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 30);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(cal.getTime()));
Use this method
public static Date addDaystoGivenDate(Integer days, Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}

Calendar.MONTH setting to wrong month

//this month
SimpleDateFormat df_formonth = new SimpleDateFormat("MMM");
c.set(Calendar.MONTH, 5); //integer to be changed upon click - maybe month counter from now
String currmonth = df_formonth.format(c.getTime());
This should return June since we index months from 0 to 11
but it returns july
any solutions or other ways to fix this?
Because today's date is the 31st of August and June only has 30 days, the month is automatically incremented to the following month giving July.
To solve you can set the date before setting the month
c.set(Calendar.DATE, 30);
c.set(Calendar.MONTH, Calendar.JUNE);
Also I suggest using Calendar constants for clarity
Well known issue when you are working with dates at the end of the month (31st of Aug).
You should explicitly set the date.
For example read here for details:
http://www.coderanch.com/t/385083/java/java/java-util-Calendar-set
You can try the following:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.MONTH, Calendar.JUNE);

How to set a Java Date object's value to yesterday? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get yesterday's date using Date
What is an elegant way set to a Java Date object's value to yesterday?
With JodaTime
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minus(Period.days(1));
System.out.printf("Today is : %s, Yesterday : %s", today.toString("yyyy-MM-dd"), yesterday.toString("yyyy-MM-dd"));
Do you mean to go back 24 hours in time.
Date date = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);
or to go back one day at the time same time (this can be 23 or 25 hours depending on daylight savings)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
These are not exactly the same due to daylight saving.
Convert the Date to a Calendar object and "roll" it back a single day. Something like this helper method take from here:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime(c.getTime().getTime());
}
For your specific case, just pass in days as -1 and you should be done. Just make sure you take into consideration the timezone/locale if doing extensive date specific manipulations.
you can try the follwing code:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
As many people have already said use Calendar rather than date.
If you find you really want to use dates:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.getTime();//returns a Date object
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DAY_OF_MONTH, -1);
cal1.getTime();//returns a Date object
I hope this helps.
tomred
You can try the following example to set it to previous date.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today's date is " +dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));

Categories

Resources