开发者

Find name of day by year, month and day [duplicate]

开发者 https://www.devze.com 2023-03-22 18:27 出处:网络
This question already has answers here: How to determine day of week by passing specific date? 开发者_运维百科
This question already has answers here: How to determine day of week by passing specific date? 开发者_运维百科 (28 answers) Closed 8 years ago.

If I have int year, int month, int day in Java, how to find name of day ? Is there already some functions for this ?


Use SimpleDateFormat with a pattern of EEEE to get the name of the day of week.

// Assuming that you already have this.
int year = 2011;
int month = 7;
int day = 22;

// First convert to Date. This is one of the many ways.
String dateString = String.format("%d-%d-%d", year, month, day);
Date date = new SimpleDateFormat("yyyy-M-d").parse(dateString);

// Then get the day of week from the Date based on specific locale.
String dayOfWeek = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);

System.out.println(dayOfWeek); // Friday

Here it is wrapped all up into a nice Java class for you.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class DateUtility
{

    public static void main(String args[]){
        System.out.println(dayName("2015-03-05 00:00:00", "YYYY-MM-DD HH:MM:ss"));
    }

    public static String dayName(String inputDate, String format){
        Date date = null;
        try {
            date = new SimpleDateFormat(format).parse(inputDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);
    }
}


You can do something like this to get the names of the days of the week for different locales.

Here's the important part:

DateFormatSymbols dfs = new DateFormatSymbols(usersLocale);
String weekdays[] = dfs.getWeekdays();

That can be combined with this:

Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_WEEK);

To get what you're looking for:

String nameOfDay = weekdays[day];


Construct a GregorianCalendar with the year, month and day, then query it to find the name of the day. Something like this:

int year = 1977;
int month = 2;
int dayOfMonth = 15;
Calendar myCalendar = new GregorianCalendar(year, month, dayOfMonth);

int dayOfWeek = myCalendar.get(Calendar.DAY_OF_WEEK);

Note that the day of week is returned as an int representing the ordinal of the day in the locale's week day representation. IE, in a locale where the weekday starts on Monday and ends on Sunday, a 2 would represent Tuesday, whereas if the locale weekday starts on Sunday then that same 2 would represent Monday.

Edit

And since there is alot of answer editing going on, allow me to add the following:

DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
String dayOfMonthStr = symbols.getWeekdays()[dayOfMonth];

Thought to be honest, I like the SimpleDateFormatter approach better, because it encapsulates the very same code as I've shown above. Silly me to forget all about it.


You can use the Calendar Object to find this.

Once you create the calendar instance you get the DAY_OF_WEEK (which is an int) then you can find the day from there)

You can use a switch statement like so:

import java.util.*;

public class DayOfWeek {

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DAY_OF_WEEK);
        System.out.print("Today is ");
        switch (day) {
            case 1:
                System.out.print("Sunday");
                break;
            case 2:
                System.out.print("Monday");
                break;
            case 3:
                System.out.print("Tuesday");
                break;
            case 4:
                System.out.print("Wednesday");
                break;
            case 5:
                System.out.print("Thursday");
                break;
            case 6:
                System.out.print("Friday");
                break;
            case 7:
                System.out.print("Saturday");
        }
        System.out.print(".");
    }
}


The name of the week day differs per locale. So you have to use a DateFormat with the proper locale. For example:

SimpleDateFormat format = new SimpleDateFormat("EEEE");
System.out.println(format.format(date));

The Date object can be obtained in multiple ways, including the deprecated Date(..) constructor, the Calendar.set(..) methods or joda-time DateTime. (for the latter you can use joda-time's own DateTimeFormat)


Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 22); //Set Day of the Month, 1..31
cal.set(Calendar.MONTH,6); //Set month, starts with JANUARY = 0
cal.set(Calendar.YEAR,2011); //Set year
System.out.println(cal.get(Calendar.DAY_OF_WEEK)); //Starts with Sunday, 6 = friday


This kind of date-time work is easier when using the Joda-Time library. A simple one-liner.

String dayOfWeek = new LocalDate( 2014, 1, 2 ).dayOfWeek().getAsText( java.util.Locale.ENGLISH );

System.out.println( "dayOfWeek: " + dayOfWeek );

When run…

dayOfWeek: Thursday


new GregorianCalendar().setTime(new Date()).get(DAY_OF_WEEK)

That gives you a number, Calendar.SUNDAY == 1, Calendar.MONDAY == 2, ...


Yes, but it's a rather long process with the JDK. JodaTime may be a better choice (I haven't used it).

First, you get a Calendar object, so that you can construct a date from day/month/year/timezone. Do not use one of the deprecated Date constructors.

Then get a Date object from that calendar, and pass it to SimpleDateFormat. Note that the format objects are not threadsafe.

  // by default, this Calendar object will have the current timezone
  Calendar cal = GregorianCalendar.getInstance();
  cal.set(2011, 6, 22);

  // this formatter will have the current locale
  SimpleDateFormat format = new SimpleDateFormat("EEEE");

  System.out.println(format.format(cal.getTime()));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号