Get a day from week based on Unix timestamp - java

The Unix timestamp is 1417029117, which is 11/26/2014, Wednesday.
long timestamp = 1417029117l*1000l;
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
System.out.println("current day is "+cal.get(Calendar.DAY_OF_WEEK));
System.out.println("current month is "+cal.get(Calendar.MONTH));
And I got the results as follows:
current day is 4
current month is 10
Any explanation? If January is 0 then the month is fine. But why the day is 4?

First day of the week is Sunday. So, Wednesday is 4. See Calendar#DAY_OF_WEEK and Constant Field Values, Calendar#WEDNESDAY, it's plain out there in the documentation.

Related

Getting the week number for a date (week starting on Wednesday)

LocalDate initial = LocalDate.now();
DayOfWeek dayOfWeek = DayOfWeek.WEDNESDAY;
WeekFields weekFields = WeekFields.of(dayOfWeek, 1);
int weekNo = date.get(weekFields.weekOfWeekBasedYear());
System.out.println("Week No"+weekNo);
I am using the above code for date 2018-07-29. I expect week no 30, but I get 31.
What am I missing here to get the result of 30?
If you expected output as according to ISO-8601, where current week is week 30, you'd need to follow this:
Week number according to the ISO-8601 standard, weeks starting on Monday. The first week of the year is the week that contains that year's first Thursday (='First 4-day week').
This is implemented by WeekFields.ISO.
If instead, you want the week to start on WEDNESDAY, you only need to change the minimalDaysInFirstWeek from 1 to 4 (='First 4-day week'):
LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(DayOfWeek.WEDNESDAY, 4);
int weekNo = date.get(weekFields.weekOfWeekBasedYear());
System.out.println("Week No " + weekNo);

Date using 'YYYY'

This is a question related to Java Date year calculation is off by year for two days
I understand the problem appeared from using 'YYYY' instead of 'yyyy', whereby 'YYYY' refers to calendar year instead of the actual year, resulting in the year being wrong if the dates fell onto the first week of January's calendar year.
I tried to read further and understand the problem in
https://docs.oracle.com/javase/9/docs/api/java/util/GregorianCalendar.html#week_year
And it says
"A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar year values."
I have been trying to see if there are any time of the year where 01-Jan-XXXX is actually displayed as 01-Jan-(XXXX-1) but have not managed to find any. Is there a case where this may happen?
I did something simple to take string dates and print out using YYYYMMdd format
public static void main(String[] args) throws ParseException
{
Calendar testCalendar = Calendar.getInstance();
System.out.println("First day of the week: " + testCalendar.getFirstDayOfWeek());
System.out.println("Minimal Days in First Week: " + testCalendar.getMinimalDaysInFirstWeek());
SimpleDateFormat YYYYMMdd= new SimpleDateFormat("YYYYMMdd");
String dateString = "01/01/2016";
Date date = new Date();
date = new SimpleDateFormat("dd/MM/yyyy").parse(dateString);
testCalendar.setTime(date);
int week = testCalendar.get(Calendar.WEEK_OF_YEAR);
String date2 = YYYYMMdd.format(date);
System.out.println("Week Number: " + week);
System.out.println("Date: " + date2);
}
And the output was
First day of the week: 1
Minimal Days in First Week: 1
Week Number: 1
Date: 20161231
If I change the date to "01/01/2016"
The output was
First day of the week: 1
Minimal Days in First Week: 1
Week Number: 1
Date: 20160101
So 01/01/2016 is the first week of of 2016, and not week 53 of 2015.
For a concrete answer, the following table shows January 1 for each year from 2010 through 2020 with day-of-week, week-based year and week number in ISO (the international standard) and in the US.
Year DOW ISO US
2010 Fri 2009-53 2010-01
2011 Sat 2010-52 2011-01
2012 Sun 2011-52 2012-01
2013 Tue 2013-01 2013-01
2014 Wed 2014-01 2014-01
2015 Thu 2015-01 2015-01
2016 Fri 2015-53 2016-01
2017 Sun 2016-52 2017-01
2018 Mon 2018-01 2018-01
2019 Tue 2019-01 2019-01
2020 Wed 2020-01 2020-01
As you can see, internationally January 1 regularly falls in week 52 or 53 of the previous year, while in the US it always falls in week 1 of its own year.
International rule: Week 1 is the first one that contains at least 4 days of the new year. In other words, a week belongs in the year where most of its days are. In yet other words, week 1 is the one that holds the first Thursday of the year (since weeks begin on Mondays). This implies that when January 1 is a Friday, Saturday or Sunday, it belongs to the last week of the previous year.
US rule: Week 1 is the week that contains January 1. That January 1 always falls in week 1 of its own year follows from this definition (weeks begin on Sundays).
The table came out of this snippet:
System.out.println("Year DOW ISO US");
for (int year = 2010; year <= 2020; year++) {
LocalDate jan1 = LocalDate.of(year, Month.JANUARY , 1);
System.out.format(Locale.ROOT, "%4d %3s %4d-%02d %4d-%02d%n",
year, jan1.getDayOfWeek().getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ROOT),
jan1.get(WeekFields.ISO.weekBasedYear()), jan1.get(WeekFields.ISO.weekOfWeekBasedYear()),
jan1.get(WeekFields.SUNDAY_START.weekBasedYear()), jan1.get(WeekFields.SUNDAY_START.weekOfWeekBasedYear()));
}
I am of course using java.time, the modern Java date and time API. I warmly recommend it over the outdated Calendar, SimpleDateFormat and Date.
No. The week year is only to be used in conjunction with the week. For example the 1st January 2016 (a Friday) is in the 53. week of 2015. It will never be displayed as 1. January 2015 since that would be ambiguous.
Calendar d = Calendar.getInstance();
d.set(Calendar.YEAR, 2016)
d.set(Calendar.MONTH, Calendar.JANUARY);
d.set(Calendar.DATE, 1);
SimpleDateFormat ft = new SimpleDateFormat("w-YYYY");
ft.format(d.getTime());
// => "53-2015"
In the US, the first week of the year is defined as being the week containing January 1*.
As a consequence, the week-year for January 1 will always be the same as the calendar year, in the US.
*https://en.wikipedia.org/wiki/Week#Week_numbering

How to get week of selected date in java?

How to get week of particular selected date?
For Example:
My week will start from Monday and ends on Sunday.
So lets say i have selected 25 July 2017. So i want what was the date on monday of that week and what is the date on upcoming Sunday of that week.
The answer should be :: Monday -- 24 July 2017 AND Sunday-- 30 July 2017.
I am not able to find a simple way to get it.
You can see this. It is for the present date.
Calendar cal = Calendar.getInstance();
int week = cal.get(Calendar.WEEK_OF_MONTH);
int day = cal.get(Calendar.DAY_OF_WEEK);
System.out.println(day);
Date mondayDate = null;
if (day > 2) {
int monday = day - 2;
cal.add(Calendar.DATE, -monday);
mondayDate = cal.getTime();
} else {
// cal.add(Calendar.DATE,);
mondayDate = cal.getTime();
}
int sunday = 7 - day + 1;
cal.add(Calendar.DATE, +sunday);
Date sundaydate = cal.getTime();
System.out.println(mondayDate);
System.out.println(sundaydate);
}
In this, we are finding the day of the week.Today we will get
day=2.
Now for monday,we will first check days.
if day=1, means it is sunday.
if day=2, means it is monday.
so for day>2, we are getting date of (day-2) days back. For today, day=1. hence mondaydate= 23 July,2017.
Similarily for sunday, we are getting date of (7-day+1) days later. For today, sunday=5, so after +6, sundaydate= 31 july,2017
Hope this helps :)
You can get like this :
String date = (String) android.text.format.DateFormat.format("dd", date);
String dayOfTheWeek = (String) DateFormat.format("EEEE", date);
For next Sunday you can calculate as per dayOfTheWeek.

Day and month incorrect when setting next day of date using Calendar

//fetch date and convert to date type
String DateString = Integer.toString(getDay()) + "/" + Integer.toString(getMonth()) + "/" + Integer.toString(getYear());
DateFormat parser = new SimpleDateFormat("dd/MM/yyyy"); //current format of date
Date date = (Date) parser.parse(DateString); //convert string to date
//calculate next day
Calendar cal = Calendar.getInstance();
cal.setTime(date); //set calendar time to chosen date
cal.add(Calendar.DATE, 1); //add 1 day to calendar date
//set object to next day
parser.format(cal.getTime()); //set format to dd/MM/yyyy
setDay(cal.get(cal.DAY_OF_MONTH));
setMonth(cal.get(cal.MONTH));
setYear(cal.get(cal.YEAR));
I set a date to 23 October 2002. I want to set it to the next day using the above method. It shows 24 September 2002 instead of 24 October 2002. Why is it adding 1 to the day and removing 1 from the month?
The reason is that months are zero based index ie, they start from 0 instead of 1 so January is 0, Feb is 1, march is 2 and .....Decemeber is 11
From the Oracle docs:
A month is represented by an integer from 0 to 11; 0 is January, 1 is
February, and so forth; thus 11 is December.
EDIT:-
Trying to give the reason for why months start with zero.
The tm structure which is defined in time.h has an integer field tm_mon with the range of 0-11, so I guess this has been taken from the C language. One other reason which might sound wierd but can be reason that since we have names of the month but for days(1,2,3...30,31) we dont have any names

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.

Categories

Resources