Java 从星期几中获取 Joda Time 的日期名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20907809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:14:17  来源:igfitidea点击:

From the day week number get the day name with Joda Time

javajodatime

提问by Odyssee

I have a day of the weeknumber: 2 (which should match to Tuesday if week start on Monday).

我有一个星期几:2(如果一周从星期一开始,它应该与星期二匹配)。

From this number is there a way to get the name of the day in Java using Joda Time? In javascript it has been quite easy to do it using moment.js:

从这个数字有没有办法使用 Joda Time 在 Java 中获取当天的名称?在 javascript 中,使用 moment.js 很容易做到:

moment().day(my number)

采纳答案by Meno Hochschild

Joda-Time

乔达时间

At least this works, although I consider it as not so nice:

至少这是有效的,尽管我认为它不太好:

LocalDate date = new LocalDate();
date = date.withDayOfWeek(2);
System.out.println(DateTimeFormat.forPattern("EEEE").print(date));

Unfortunately Joda-Timedoes not offer an enum for the day of week (java.time does). I have not quickly found another way in the huge api. Maybe some Joda-experts know a better solution.

不幸的是,Joda-Time不提供星期几的枚举(java.time 提供)。我还没有很快在巨大的api中找到另一种方法。也许一些 Joda 专家知道更好的解决方案。

Added (thanks to @BasilBourque):

添加(感谢@BasilBourque):

LocalDate date = new LocalDate();
date = date.withDayOfWeek(2);
System.out.println(date.dayOfWeek().getAsText());

java.time

时间

In java.time(JSR 310, Java 8 and later), use the DayOfWeekenum.

java.timeJSR 310、Java 8 及更高版本)中,使用enumDayOfWeek

int day = 2;
System.out.println( DayOfWeek.of(2).getDisplayName(TextStyle.FULL, Locale.ENGLISH) );
// Output: Tuesday

You can use a particular enum instance directly rather than a magic numberlike 2. The DayOfWeekenum provides an instance for each day of week such as DayOfWeek.TUESDAY.

您可以使用特定的枚举实例,而不是直接一个神奇的数字一样2。该DayOfWeek枚举为一周的每一天如一个实例DayOfWeek.TUESDAY

System.out.println( DayOfWeek.TUESDAY.getDisplayName(TextStyle.FULL, Locale.ENGLISH) );
// Output: Tuesday

Old JDK

旧版 JDK

For making it complete, here the solution of old JDK:

为了使它完整,这里是旧JDK的解决方案:

int day = 2;
DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ENGLISH);
System.out.println(dfs.getWeekdays()[day % 7 + 1]);

回答by jjurm

You can do it yourself

你可以自己做

String[] dayNames = new String[]{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
String name = dayNames[day-1];

And this even does not require any library :)

这甚至不需要任何库:)

回答by M. Hig

Using Joda you can do this:

使用 Joda,您可以执行以下操作:

 DateTime curTime = new DateTime();
 curTime.dayOfWeek().getAsText(Locale.ENGLISH);

Replace Localewith whatever your Locale is.

替换Locale为您的语言环境。

Should return a week day name such as Monday or Tuesday

应该返回一个工作日名称,例如 Monday or Tuesday