从当天的周数获得Joda Time的日期名称 [英] From the day week number get the day name with Joda Time

查看:119
本文介绍了从当天的周数获得Joda Time的日期名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有星期几号码:2(如果星期一星期开始,则应该与星期二匹配)。

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

来自此number是否有办法使用Joda Time获取Java中的当天名称?
在javascript中使用moment.js很容易做到:

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:

moment().day(my number)


推荐答案

Joda-Time



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

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

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

Unfortunately Joda-Time does 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.

已添加(感谢@BasilBourque):

Added (thanks to @BasilBourque):

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



java.time



java.time JSR 310 ,Java 8及更高版本),使用 DayOfWeek 枚举

java.time

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

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

你可以直接使用特定的枚举实例而不是< a href =https://en.wikipedia.org/wiki/Magic_number_%28programming%29\"rel =noreferrer>幻数,如 2 DayOfWeek enum为一周中的每一天提供一个实例,例如 DayOfWeek.TUESDAY

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

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



旧JDK



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

Old JDK

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

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

这篇关于从当天的周数获得Joda Time的日期名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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