从 GregorianCalendar 获取星期几
我有一个日期,我需要知道星期几,所以我使用了 GregorianCalendar 对象,但我得到了一些不正确的日期。
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
我做错了什么?
谢谢!
编辑解决方案:
mont--;
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
if(i == 2){
dayOfTheWeek = "Mon";
} else if (i==3){
dayOfTheWeek = "Tue";
} else if (i==4){
dayOfTheWeek = "Wed";
} else if (i==5){
dayOfTheWeek = "Thu";
} else if (i==6){
dayOfTheWeek = "Fri";
} else if (i==7){
dayOfTheWeek = "Sat";
} else if (i==1){
dayOfTheWeek = "Sun";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Joda-Time
我使用 Joda-Time 库来执行所有日期/时间相关的操作。 Joda 会考虑您的区域设置并相应地获取结果:
或
星期几 (int):
使用
toString()
和DateTimeFormat
选项:Joda-Time
I use Joda-Time library for all date/time related operations. Joda takes into account you locale and gets results accordingly:
or
Day of week (int):
Day of week (short String) using
toString()
andDateTimeFormat
options:太长了;博士
java.time
转换麻烦的旧遗留
通过调用添加到旧类中的新方法,将 java.util.GregorianCalendar
对象转换为现代 java.time 对象。获取该时区该时刻的
DayOfWeek
枚举对象。在代码中传递这些
DayOfWeek
对象,而不是传递像 1-7 这样的整数或像“MON”这样的字符串。通过使用枚举对象,您可以使代码更加自文档化、提供类型安全并确保有效值的范围。为了向用户展示,请要求
DayOfWeek
对象将星期几的名称翻译为Locale
中定义的人类语言。关于 java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如
java.util.Date
,日历
, & ;SimpleDateFormat
。Joda-Time 项目,现已在 维护模式,建议迁移到java.time 类。
要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310。
您可以直接与数据库交换java.time对象。使用符合 JDBC 驱动程序 /jeps/170" rel="nofollow noreferrer">JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。
从哪里获取 java.time 类?
tl;dr
java.time
Convert the troublesome old legacy
java.util.GregorianCalendar
object to a modern java.time object by calling new methods added to the old class.Get the
DayOfWeek
enum object for that moment in that time zone.Pass these
DayOfWeek
objects around your code rather than passing integers like 1-7 or strings like "MON". By using the enum objects you make your code more self-documenting, provide type-safety, and ensure a range of valid values.For presentation to the user, ask the
DayOfWeek
object to translate the name of the day of the week to a human language defined in aLocale
.About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?