How to Get the Day of Week and the Month of the Year

How to get the day of week and the month of the year?

Yes, you'll need arrays.

var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];

Or you can use the date.js library.


EDIT:

If you're going to use these frequently, you may want to extend Date.prototype for accessibility.

(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

Date.prototype.getMonthName = function() {
return months[ this.getMonth() ];
};
Date.prototype.getDayName = function() {
return days[ this.getDay() ];
};
})();

var now = new Date();

var day = now.getDayName();
var month = now.getMonthName();

How to get day of the week, day of month, month and year?

java.time through desugaring

Consider using java.time, the modern Java date and time API, for your date work. Let’s first see how checking the day of the week goes:

    LocalDate today = LocalDate.now(ZoneId.systemDefault());

switch (today.getDayOfWeek()) {
case MONDAY:
System.out.println("Set image to Monday’s image here");
break;

case TUESDAY:
System.out.println("Set image to Tuesday’s image here");
break;

default:
throw new AssertionError("Unsupported day of week: " + today.getDayOfWeek());
}

I trust you to fill out the remaining five days of the week yourself, and also to set the image resource of the image view as in your question. The way my code stands, when I ran it today, Monday November 1, the output was:

Set image to Monday’s image here

It works because getDayOfWeek() returns an instance of the DayOfWeek enum and Java allows us to switch on enums.

For the day of the month:

    switch (today.getDayOfMonth()) {
case 1:
System.out.println("Set image to image for 1st day of month here");
break;

case 2:
System.out.println("Set image to image for 2nd day of month here");
break;

default:
throw new AssertionError("Unsupported day of month: " + today.getDayOfWeek());
}

Set image to image for 1st day of month here

Again fill out up to 31 yourself. While a day of week is an enum, a day of a month is a plain int.

The case of the month is similar to the day of the week in that there’s an enum that we prefer to use. getMonth() returns an instance of the Month enum, and in your switch statement you will have cases JANUARY, FEBRUARY, etc.

Finally getYear() again returns an int, so the year case will be similar to the day of the month with cases 2021, 2022, etc.

Edit: you asked:

… can you give code to validate both date and month in single switch
case? … only for one case its enough for "DATE" and "MONTH"...rest i
will do it

If you’re comfortable with switch statements, you may also nest them inside each other:

    switch (today.getMonth()) {
case JANUARY:
switch (today.getDayOfMonth()) {
case 1:
System.out.println("Set image to image for 1st day of January here");
break;

// …

default:
throw new AssertionError("Unsupported day of January: " + today.getDayOfWeek());
}
break;

// …

default:
throw new AssertionError("Unsupported month: " + today.getMonth());
}

Alternative: use maps

For a slightly advanced but also very elegant solution, instead of the longish switch or if-else statement define the images to use for each day of week in an EnumMap<DayOfWeek, String> (if the image reference in R.drawable.IMAGE1 is a String, sorry, I don’t know Android so can’t tell). For the day of the month you may either use a HashMap<Integer, String> or an arrays of strings.

Edit: I think the map approaches becomes particularly appealing when it comes to combining month and day of month. I am using Java 9 syntax here and hope it works with desugaring, it’s not something I know:

private static final Map<MonthDay, String> IMAGES_PER_DAY
= Map.ofEntries(
Map.entry(MonthDay.of(Month.JANUARY, 1), "Image for Jan 1"),
Map.entry(MonthDay.of(Month.JANUARY, 2), "Image for Jan 2"),
// …
Map.entry(MonthDay.of(Month.NOVEMBER, 1), "Image for Nov 1"),
// …
Map.entry(MonthDay.of(Month.DECEMBER, 31), "Image for Dec 31"));

Now picking the right image for today’s date is pretty simple:

    String imageReference = IMAGES_PER_DAY.get(MonthDay.from(today));
System.out.println("Set image to " + imageReference);

Set image to Image for Nov 1

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • Java 8+ APIs available through desugaring
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Get Date of days of a week given year, month and week number (relative to month) in Javascript / Typescript

If you want Monday as the first day of the week, and the first week of a month is the one with the first Thursday, then you can use a similar algorithm to the year week number function.

So get the start of the required week, then just loop 7 times to get each day. E.g.

/* Return first day of specified week of month of year
**
** @param {number|string} year - year for required week
** @param {number|string} month - month for required week
** Month is calendar month number, 1 = Jan, 2 = Feb, etc.
** @param {number|string} week - week of month
** First week of month is the one with the first Thursday
** @returns {Date} date for Monday at start of required week
*/
function getMonthWeek(year, month, week) {
// Set date to 4th of month
let d = new Date(year, month - 1, 4);
// Get day number, set Sunday to 7
let day = d.getDay() || 7;
// Set to prior Monday
d.setDate(d.getDate() - day + 1);
// Set to required week
d.setDate(d.getDate() + 7 * (week - 1));
return d;
}

// Return array of dates for specified week of month of year
function getWeekDates(year, month, week) {
let d = getMonthWeek(year, month, week);
for (var i=0, arr=[]; i<7; i++) {

// Array of date strings
arr.push(d.toDateString());

// For array of Date objects, replace above with
// arr.push(new Date(d));

// Increment date
d.setDate(d.getDate() + 1);
}
return arr;
}

// Week dates for week 1 of Jan 2020 - week starts in prior year
console.log(getWeekDates(2020, 1, 1));
// Week dates for week 5 of Jan 2020 - 5 week month
console.log(getWeekDates(2020, 1, 5));
// Week dates for week 1 of Oct 2020 - 1st is a Thursday
console.log(getWeekDates(2020, 10, 1));
// Week dates for week 1 of Nov 2020 - 1st is a Sunday
console.log(getWeekDates(2020, 11, 1));

get start and end day of week by year, month and week number

You can get that start of a given month/year using moment({Object}) and then get your desired week, by adding weeks using add().

Here a live sample:

const getStartDateByWeekAndYear = function(week, year, month) {    return moment({y: year, M: month-1, d: 1})      .add(week-1, 'w').day("Monday").toDate();};
const getEndDateByWeekAndYear = function(week, year, month) { return moment({y: year, M: month-1, d: 1}) .add(week-1, 'w').day("Saturday").toDate();}
console.log( getStartDateByWeekAndYear(2, 2019, 6) );console.log( getEndDateByWeekAndYear(2, 2019, 6) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Get all the dates of the month from Day of week

You can create a function to get the list of dates of the month based on day of a particular year like

public static List<DateTime> GetDates(int year, int month,string day)
{
return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
.Where(d=>new DateTime(year, month, d).ToString("dddd").Equals(day))
.Select(d => new DateTime(year, month, d)).ToList();
}

Now call this function like

var dates=GetDates(2016,12,"Thursday");
foreach(var d in dates){
Console.WriteLine(d.ToString());
}

Output will be

12/1/2016 12:00:00 AM

12/8/2016 12:00:00 AM

12/15/2016 12:00:00 AM

12/22/2016 12:00:00 AM

12/29/2016 12:00:00 AM

Now you have complete list of dates based on a day. You can further use it based on your requirements.

Get which day of week a month starts on from given input of month and year

You can get the day of the week by using the getDay function of the Date object.

To get the first of the month create a new Date object:

var year = "2012";var month = "12";var day = new Date(year + "-" + month + "-01").getDay();// 6 - Saturdayconsole.log(day);

How to get daterange by having week number of the month and the year in Java?

Build a DateTimeFormatter that uses a default day of week as needed (start of week, e.g. Monday).

Example:

var format = new DateTimeFormatterBuilder()
.appendPattern("MMMMuuuu'W'W") // or use corresponding appends
.parseDefaulting(ChronoField.DAY_OF_WEEK, DayOfWeek.MONDAY.getValue())
.toFormatter()
.withLocale(Locale.US);
var date = LocalDate.parse("September2021W5", format);

same can be done for the end of the week, or just adding 6 days to previous result (date.plusDays(6))


MMMM is for month of year, full form

uuuu year

'W' for literal W

W for week of month

Using Locale.UK so the month gets parsed for that locale, use the one needed for the given input - to use the default system Locale, use Locale.getDefault().



Related Topics



Leave a reply



Submit