简体   繁体   中英

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

The below code is to check the day of the week, now I want to check the date, month, year ...how to modify it?

import java.util.Calendar

ImageView imageView;

Calendar cal = Calendar.getInstance();

cal.setTime(now_date);

imageView = (ImageView)findViewById(R.id.imageView);

if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
    imageView.setImageResource(R.drawable.IMAGE1);
} else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
    imageView.setImageResource(R.drawable.IMAGE2);
}

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API * .

Solution using java.time , the modern Date-Time API: Use ZonedDateTime with the applicable ZoneId and retrieve the required values from it.

Demo:

import java.time.DayOfWeek;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Specify the applicable ZoneId e.g.
        // ZonedDateTime.now(ZoneId.of("Asia/Kolkata"))
        // to get the current date-time in that timezone
        ZonedDateTime now = ZonedDateTime.now();

        DayOfWeek dow = now.getDayOfWeek();
        System.out.println(dow);

        int weekDayNum = dow.getValue();
        System.out.println(weekDayNum);

        String weekDayName = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
        System.out.println(weekDayName);

        int year = now.getYear();
        System.out.println(year);

        Month month = now.getMonth();
        System.out.println(month);

        int monthValue = month.getValue();
        System.out.println(monthValue);

        int dayOfMonth = now.getDayOfMonth();
        System.out.println(dayOfMonth);

        int dayOfYear = now.getDayOfYear();
        System.out.println(dayOfYear);
    }
}

Output:

MONDAY
1
Monday
2021
NOVEMBER
11
1
305

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time . Check this answer and this answer to learn how to use java.time API with JDBC.


* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring . Note that Android 8.0 Oreo already provides support for java.time .

Similar to DAY_OF_WEEK, you can get other fields from Calendar instance.

Please check Java Docs for more details: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Refer to the documentation https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html you can get the week, month and year in this way

Date today = new Date(); 
cal.setTime(today); 
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); 
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int dayOfYear = cal.get(Calendar.DAY_OF_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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM