Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first day of the current week and month?

Tags:

java

date

android

I have the date of several events expressed in milliseconds[1], and I want to know which events are inside the current week and the current month, but I can't figure out how to obtain the first day (day/month/year) of the running week and convert it to milliseconds, the same for the first day of the month.

[1]Since January 1, 1970, 00:00:00 GMT 
like image 234
cesarlinux Avatar asked May 30 '10 00:05

cesarlinux


People also ask

How do you determine the first day of the week?

To get the first day of the week, we subtract the day of the week from the day of the month. If the day of the week is Sunday, we subtract 6 to get Monday, if it is any other day we add 1 , because the getDay method returns a zero-based value.

How can I get current week?

Let's suppose today is Monday and the week number is 1. So, if we calculate the week number after 25 days, the week number will be 4th. According to the week number calculation: 25 days = 7 + 7 + 7 + 4 days.

How can get first and last day of current week in PHP?

$monday = date('d-m-Y',strtotime('last monday',strtotime('next monday',strtotime($date)))); You have to get next monday first then get the 'last monday' of next monday. So if the given date is monday it will return the same date not last week monday.


1 Answers

This week in milliseconds:

// get today and clear time of day Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day ! cal.clear(Calendar.MINUTE); cal.clear(Calendar.SECOND); cal.clear(Calendar.MILLISECOND);  // get start of this week in milliseconds cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); System.out.println("Start of this week:       " + cal.getTime()); System.out.println("... in milliseconds:      " + cal.getTimeInMillis());  // start of the next week cal.add(Calendar.WEEK_OF_YEAR, 1); System.out.println("Start of the next week:   " + cal.getTime()); System.out.println("... in milliseconds:      " + cal.getTimeInMillis()); 

This month in milliseconds:

// get today and clear time of day Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day ! cal.clear(Calendar.MINUTE); cal.clear(Calendar.SECOND); cal.clear(Calendar.MILLISECOND);  // get start of the month cal.set(Calendar.DAY_OF_MONTH, 1); System.out.println("Start of the month:       " + cal.getTime()); System.out.println("... in milliseconds:      " + cal.getTimeInMillis());  // get start of the next month cal.add(Calendar.MONTH, 1); System.out.println("Start of the next month:  " + cal.getTime()); System.out.println("... in milliseconds:      " + cal.getTimeInMillis()); 
like image 81
COME FROM Avatar answered Sep 25 '22 06:09

COME FROM