【问题标题】:Find name of day by year, month and day [duplicate]按年、月和日查找日的名称[重复]
【发布时间】:2011-07-22 11:39:53
【问题描述】:

如果我在 Java 中有 int year、int month、int day,如何找到日期的名称?是否已经有一些功能?

【问题讨论】:

  • 如果你找到了你的答案,你应该接受对你帮助最大的答案。
  • 现代解决方案使用java.time.LocalDateDayOfWeek 枚举。例如:LocalDate.of( y , m , d ).getDayOfWeek().getDisplayName( … )
  • LocalDate.of(year,month,day).getDayOfWeek().toString();在 java 8 中运行良好不要忘记导入 java.util.*;

标签: java


【解决方案1】:

使用SimpleDateFormatEEEE 模式来获取星期几的名称。

// 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

在这里,它被包装成一个漂亮的 Java 类。

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);
    }
}

【讨论】:

  • 应该是公认的答案!不要忘记import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;
  • 仅供参考,非常麻烦的旧日期时间类,例如 java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 现在是 legacy,被 Java 8 中内置的 java.time 类所取代,之后。见Tutorial by Oracle
【解决方案2】:

您可以使用Calendar 对象来找到它。

创建日历实例后,您将获得 DAY_OF_WEEK(它是一个 int),然后您可以从那里找到日期)

你可以使用switch语句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(".");
    }
}

【讨论】:

  • 这会给你一个int,而不是一个名字
  • 只有英文版。德语呢?
  • @Bozho,您可以更改语言,也可以将其国际化,因此它会选择语言环境并将其设置为您喜欢的任何语言
  • 这只是一个例子。用户可以使用他们想要表示的任何字符串。有关取决于语言环境的示例,请参阅我的答案。
  • 我的观点完全正确 - 你应该使用 jvm 提供的内容,而不是自己编写。
【解决方案3】:

您可以执行this 之类的操作来获取不同区域设置的星期几的名称。

这是重要的部分:

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

这可以和这个结合起来:

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

要得到你要找的东西:

String nameOfDay = weekdays[day];

【讨论】:

    【解决方案4】:

    用年、月、日构造一个 GregorianCalendar,然后查询它以找到日期的名称。像这样的:

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

    请注意,星期几以 int 形式返回,表示区域设置的工作日表示中当天的序数。 IE,在工作日从星期一开始到星期日结束的语言环境中,2 表示星期二,而如果语言环境工作日从星期日开始,则相同的 2 表示星期一。

    编辑

    由于正在进行大量的答案编辑,请允许我添加以下内容:

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

    老实说,我更喜欢 SimpleDateFormatter 方法,因为它封装了与上面显示的完全相同的代码。愚蠢的我忘了这一切。

    【讨论】:

    【解决方案5】:

    使用Joda-Time 库时,这种日期时间工作更容易。一个简单的单线。

    String dayOfWeek = new LocalDate( 2014, 1, 2 ).dayOfWeek().getAsText( java.util.Locale.ENGLISH );
    
    System.out.println( "dayOfWeek: " + dayOfWeek );
    

    运行时……

    dayOfWeek: Thursday
    

    【讨论】:

      【解决方案6】:
      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
      

      【讨论】:

        【解决方案7】:

        是的,但是使用 JDK 是一个相当长的过程。 JodaTime 可能是更好的选择(我没用过)。

        首先,你得到一个Calendar 对象,这样你就可以从日/月/年/时区构造一个日期。不要使用已弃用的 Date 构造函数之一。

        然后从该日历中获取Date 对象,并将其传递给SimpleDateFormat。请注意,格式对象不是线程安全的。

          // 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()));
        

        【讨论】:

          【解决方案8】:

          工作日的名称因地区而异。因此,您必须使用具有正确语言环境的DateFormat。例如:

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

          Date 对象可以通过多种方式获取,包括已弃用的 Date(..) 构造函数、Calendar.set(..) 方法或 joda-time DateTime。 (对于后者你可以使用joda-time自己的DateTimeFormat

          【讨论】:

            【解决方案9】:
            new GregorianCalendar().setTime(new Date()).get(DAY_OF_WEEK)
            

            这会给你一个号码,Calendar.SUNDAY == 1Calendar.MONDAY == 2,...

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-02-29
              • 2011-09-11
              • 2016-11-28
              • 1970-01-01
              • 2019-06-01
              • 1970-01-01
              • 1970-01-01
              • 2020-09-25
              相关资源
              最近更新 更多