如何通过传递特定日期来确定星期几? [英] How to determine day of week by passing specific date?

查看:27
本文介绍了如何通过传递特定日期来确定星期几?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有日期:23/2/2010"(2010 年 2 月 23 日).我想将它传递给一个返回星期几的函数.我该怎么做?

For Example I have the date: "23/2/2010" (23th Feb 2010). I want to pass it to a function which would return the day of week. How can I do this?

在这个例子中,函数应该返回 String "Tue".

In this example, the function should return String "Tue".

另外,如果只需要序号,如何检索?

Additionally, if just the day ordinal is desired, how can that be retrieved?

推荐答案

是的.取决于您的具体情况:

Yes. Depending on your exact case:

  • 你可以使用java.util.Calendar:

Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

  • 如果您需要输出为 Tue 而不是 3(星期日从 1 开始索引,请参阅 Calendar.SUNDAY),而不是通过日历,只需重新格式化字符串:new SimpleDateFormat("EE").format(date)(EE 意思是星期几,短版")

  • if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1 for Sunday, see Calendar.SUNDAY), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")

    如果你的输入是字符串,而不是 Date,你应该使用 SimpleDateFormat 来解析它:new SimpleDateFormat("dd/M/yyyy").parse(dateString)

    if you have your input as string, rather than Date, you should use SimpleDateFormat to parse it: new SimpleDateFormat("dd/M/yyyy").parse(dateString)

    您可以使用 joda-time 的 DateTime 并调用 dateTime.dayOfWeek() 和/或 DateTimeFormat.

    you can use joda-time's DateTime and call dateTime.dayOfWeek() and/or DateTimeFormat.

    从 Java 8 开始,您现在可以使用 java.time 包代替 joda-time

    edit: since Java 8 you can now use java.time package instead of joda-time

    这篇关于如何通过传递特定日期来确定星期几?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆