This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calendar returns wrong month
I want to retrieve the date and time for my application, for which I wrote the following code
Calendar c = Calendar.getInstance();
System.err.println("Date is: " + c.get(Calendar.DATE));
System.err.println("Month is: " + c.get(Calendar.MONTH));
System.err.println("Year is: " + c.get(Calendar.YEAR));
System.err.println("Hour is: " + c.get(Calendar.HOUR_OF_DAY));
However the preceding code snippet is providing incorrect result.
SEVERE: Date is: 31
SEVERE: Month is: 11
SEVERE: Year is: 2012
SEVERE: Hour is: 17
NOTE: The time on my machine is perfect, no problem there
You are expecting 12 instead of 11 for the month.
c.get(Calendar.MONTH) returns 0 based index.
From the javadoc :
public static final int MONTH
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Month is zero indexed. So, 11 means its December.
The output that you are getting is correct.
I think you are confused why you are getting month as 11 instead of 12. Right? If that is the question then don't bother. Months are 0 based and hence 0 is January, 1 is Feb and so on...
So output as 11 means is December.
Read Docs
If you want proper month with wording as month, use below.
Calendar rightNow = Calendar.getInstance();
java.text.SimpleDateFormat df1 = new java.text.SimpleDateFormat("MM");
java.text.SimpleDateFormat df2 = new java.text.SimpleDateFormat("MMM");
java.text.SimpleDateFormat df3 = new java.text.SimpleDateFormat("MMMM");
System.out.println(df1.format(rightNow.getTime()));
System.out.println(df2.format(rightNow.getTime()));
System.out.println(df3.format(rightNow.getTime()));
it will give
12
Dec
December
Demo
Note: In demo you will see Jan 2013 as the server of this site is somewhere where 2013 already begun. World Time
Related
I'm trying to write an application that calculates the week number according to the broadcast calendar. The Wikipedia definition says:
Every week in the broadcast calendar starts on a Monday and ends on a Sunday
[...] the first week of every broadcast month always contains the Gregorian calendar first of the month
So I thought I could use WeekFields class and tried implementing it this way:
val broadcastCalendar = WeekFields.of(DayOfWeek.MONDAY, 1)
val march1 = LocalDate.of(2022, 3, 1)
val weekOfMarch1 = march1.get(broadcastCalendar.weekOfYear())
println("March 1 2022: $weekOfMarch1") // 10
This works fine most of the time but when trying to figure out the week numbers at the end and beginning of the year it fails:
val lastDayOf2022 = LocalDate.of(2022, 12, 31)
val lastWeekOf2022 = lastDayOf2022.get(broadcastCalendar.weekOfYear())
val firstDayOf2023 = LocalDate.of(2023, 1, 1)
val firstWeekOf2023 = firstDayOf2023.get(broadcastCalendar.weekOfYear())
println("last week of 2022: $lastWeekOf2022") // 53
println("first week of 2023: $firstWeekOf2023") // 1
According to Wikipedia's definition, the last week of 2022 should be 52 (Dec 19 - Dec 25) and the first one in 2023 should be 1 (Dec 26 - Jan 1) - see here.
How can I use WeekFields (or any other way) to fetch the correct week number?
From these quotes in the Wikipedia article, it seems like this calendar system uses a week-based year.
For example, if January 1 falls on a Saturday, then the broadcast calendar year would begin on the preceding Monday, December 27.
Broadcast calendar years can have either 52 or 53 weeks.
Because of this is, you should use weekOfWeekBasedYear:
val broadcastCalendar = WeekFields.of(DayOfWeek.MONDAY, 1)
val lastDayOf2022 = LocalDate.of(2022, 12, 31)
val lastWeekOf2022 = march1.get(broadcastCalendar.weekOfWeekBasedYear())
println(lastWeekOf2022) // 1
This represents the concept of the count of weeks within the year where weeks start on a fixed day-of-week, such as Monday and each week belongs to exactly one year.
This question already has answers here:
Difference between 'YYYY' and 'yyyy' in NSDateFormatter
(4 answers)
Closed 3 years ago.
Due to the new year,I detected a bug in my project.
I am showing date and time in my order history using the following code:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a MM/dd/YY", Locale.US).withZone(ZoneId.systemDefault());
String formattedOrderDate = formatter.withZone(ZoneId.of(order.timeZone)).format(order.order.pickupAt);
textView.setText(formattedOrderDate );
Here are the values received from server:
order.order.pickupAt = {ZonedDateTime#8390} "2020-01-02T17:50Z"
order.timeZone = "America/Denver"
But the output is not showing the perfect year for the end of December:
As you can clearly see, year 2019 is showing as 2020.
But it is only showing for the last of December.Another order from mid of December is showing the correct date(year).
I am not able to detect what is going wrong over here.I am suspecting that this might be due to the timezone(America/Denver).But I have changed the timezone to my local timezone,still it is showing 2020 instead of 2019.
Use yy instead of YY
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a MM/dd/yy", Locale.US).withZone(ZoneId.systemDefault());
String formattedOrderDate = formatter.withZone(ZoneId.of(order.timeZone)).format(order.order.pickupAt);
textView.setText(formattedOrderDate );
YY is for week-based calendar year and yy is for calendar year. Last few days of December was actually the first week of 2020, so it is showing 2020 for those days.
Change your code to use yy, then it will show correct year -
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a MM/dd/yy", Locale.US).withZone(ZoneId.systemDefault());
This question already has answers here:
Java GregorianCalendar and Calendar misplace weekends, days in a month for August and September, 2010
(3 answers)
Closed 8 years ago.
Hi i'm trying to get the date which is current date minus 4
Today current date is Tue Nov 04 16:35:34 IST 2014
what i'm doing is
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days);
System.out.println("new date "+" "+cal.get(cal.YEAR)+" "+cal.get(cal.MONTH)+" "+cal.get(cal.DAY_OF_MONTH));
This is the output i'm getting
new date 2014 9 31 (but the expected is 2014 10 31)
I don't know what went wrong. Can someone help me with this?
Month is Calendar API start in 0. So January is 0, February is 1, etc...
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#MONTH
I have the following:
Date now = new Date();
Date futureDate = new Date(now.getYear(), now.getMonth(), now.getDay() + 30);
I want to set the future date value to be 30 days in the future, based on the current date (now).
When I debug this, now is the correct date, and the futureDate is:
Sat Jan 05 00:00:00 EST 2013
Today's date, the value of now is: Sat Dec 29 17:31:58 EST 2012.
This doesn't make sense to me?
I'm using util.Date.
Because getDay() returns day of the week, not day of the month.
So your
now.getDay() + 30
becomes Saturday + 30 = 6 + 30 = 36th December = 5th January
A quick fix would be to replace your code with:
now.getDate() + 30
But as others already suggest, java.util.Date is kind of deprecated. And you should use Calendar.add(). So your code would become something like:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, +30);
You should use Calendar and its method Calendar.add
If you want to use Date, you'll see working with adding days is all kinds of deprecated:
http://docs.oracle.com/javase/7/docs/api/java/util/Date.html
Use new Date(now.getTime() + (MILLISECONDS_IN_DAY * 30)) instead. Or if you're not stuck with Date, use Calendar.
Not only is that constructor deprecated, it only accepts valid days (1-31).
try using java.util.Calendar instead.
Date is not supposed to be used for such calculations.
Have a look at JodaTime which is exelent for such things.
I'm having some trouble with Java's Calendar. I'm parsing some data from a txt file, and need to create a date. After completion of the following code:
tmpYear = Double.parseDouble(row[yearIndex]);
tmpMonth = Double.parseDouble(row[monthIndex]);
tmpDay = Double.parseDouble(row[dayIndex]);
if(timeIndex != -1)
tmpTime = Double.parseDouble(row[timeIndex]);
if(secondsIndex != -1)
tmpSeconds = Double.parseDouble(row[secondsIndex]);
I can debug and see that the variables are as follows:
tmpYear == 2010
tmpMonth == 12
tmpDay == 30
tmpTime == 15 (This is the hour of the day)
tmpSeconds == 0
But when running the following code:
cal.set((int)tmpYear,(int)tmpMonth,(int)tmpDay,(int)tmpTime,
(int)((tmpTime - (int)tmpTime)*100),(int)tmpSeconds);
System.out.println(cal.getTime().toString());
I'm getting this for an output:
Sun Jan 30 15:00:00 CST 2011
Can someone explain what a possible reason for this would be? Thank you all in advance for the help!
months are indexed 0-11 instead of 1-12.
0 = January
1 = February
...
11 = December
Use tmpMonth = value -1 instead.
I believe the month's value starts at 0 rather than 1 so it interprets 0 as Jan, 1 as Feb ... and then Jan again as 12.
From the API:
month - the value used to set the
MONTH time field. Month value is
0-based. e.g., 0 for January.
When you set the Calendar.MONTH field, it is zero-based. {January=0... December=11}
The reason is quite simple: design fault in the Calendar API. That's why the JSR 310 is on its way in order to improve the java support for dates.
Technically, the authors of the class thought it was good to use only static fields. So what you need to do is to use the following:
calendar = ...
calendar.setMonth(Calendar.JANUARY);
They didn't think that people might need dynamic settings to a calendar, just like you need (and most of us, for that matters).
The month values go from 0 (January) to 11 (December). Try using ((int) tmpMonth) - 1 when setting the month to get December.