Java:从任何日期获取周数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16418661/
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
Java: Get week number from any date?
提问by Boxiom
I have a small program that displays the current week from todays date, like this:
我有一个小程序,显示从今天的日期开始的当前周,如下所示:
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);
And then a JLabel that displays the week number:
然后是一个显示周数的 JLabel:
JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));
So right now I'd like to have a JTextField where you can enter a date and the JLabel will update with the week number of that date. I'm really not sure how to do this as I'm quite new to Java. Do I need to save the input as a String? An integer? And what format would it have to be (yyyyMMdd etc)? If anyone could help me out I'd appreciate it!
所以现在我想要一个 JTextField,您可以在其中输入日期,JLabel 将使用该日期的周数进行更新。我真的不知道如何做到这一点,因为我对 Java 很陌生。我需要将输入保存为字符串吗?一个整数?它必须是什么格式(yyyyMMdd 等)?如果有人可以帮助我,我将不胜感激!
采纳答案by Andreas Fester
Do I need to save the input as a String? An integer?
我需要将输入保存为字符串吗?一个整数?
When using a JTextField
, the input you get from the user is a String
, since the date can contain characters like .
or -
, depending on the date format you choose. You can of course also use some more sophisticated input methods, where the input field already validates the date format, and returns separate values for day, month and year, but using JTextField
is of course easier to start with.
使用 a 时JTextField
,您从用户那里获得的输入是 a String
,因为日期可以包含类似.
或 的字符-
,具体取决于您选择的日期格式。您当然也可以使用一些更复杂的输入法,其中输入字段已经验证了日期格式,并返回日、月和年的单独值,但使用JTextField
当然更容易开始。
And what format would it have to be (yyyyMMdd etc)?
它必须是什么格式(yyyyMMdd 等)?
This depends on your requirements. You can use the SimpleDateFormatclass to parse any date format:
这取决于您的要求。您可以使用SimpleDateFormat类来解析任何日期格式:
String input = "20130507";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
But more likely you want to use the date format specific to your locale:
但更有可能您想使用特定于您的语言环境的日期格式:
import java.text.DateFormat;
DateFormat defaultFormat = DateFormat.getDateInstance();
Date date = defaultFormat.parse(input);
To give the user a hint on which format to use, you need to cast the DateFormat
to a SimpleDateFormat
to get the pattern string:
要向用户提示使用哪种格式,您需要将 a 强制转换DateFormat
为 aSimpleDateFormat
以获取模式字符串:
if (defaultFormat instanceof SimpleDateFormat) {
SimpleDateFormat sdf = (SimpleDateFormat)defaultFormat;
System.out.println("Use date format like: " + sdf.toPattern());
}
The comment by @adenoyelle above reminds me: Write unit tests for your date parsing code.
上面@adenoyelle 的评论提醒我:为您的日期解析代码编写单元测试。
回答by Madhusudan Joshi
You can use that, but you have to parse the date value to proper date format using SimpleDateFormatter
of java API
. You can specify any format you want. After that you can do you manipulation to get the week of the year.
您可以使用它,但您必须使用SimpleDateFormatter
of将日期值解析为正确的日期格式java API
。您可以指定所需的任何格式。之后,您可以进行操作以获得一年中的一周。
回答by Bill the Lizard
You can store the date as a String, and the user can enter it in pretty much any format you specify. You just need to use a DateFormat
object to interpret the date that they enter. For example, see the top answeron Convert String to Calendar Object in Java.
您可以将日期存储为字符串,并且用户可以以您指定的几乎任何格式输入它。您只需要使用一个DateFormat
对象来解释他们输入的日期。例如,看到最多的回答上字符串转换为Java中日历对象。
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));
To read the date from a JTextField
, you could replace that with something like:
要从 a 读取日期JTextField
,您可以将其替换为:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // or any other date format
cal.setTime(sdf.parse(dateTextField.getText()));
Then you just need to read the week number from cal
in the same way you showed in the question. (This is a simplified example. You'd need to handle the potential ParseException
thrown by the DateFormat
parse
method.)
然后你只需要cal
按照你在问题中显示的相同方式读取周数。(这是一个简化的示例。您需要处理ParseException
该DateFormat
parse
方法抛出的潜力。)
回答by user3408091
public static int getWeek() {
return Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
}
Works fine and return week for current realtime
工作正常并返回当前实时的一周
回答by user667
Java 1.8 provides you with some new classes in package java.time
:
Java 1.8 在 package 中为您提供了一些新类java.time
:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.IsoFields;
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.printf("Week %d%n", now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
Most legacy calendars can easily be converted to java.time.ZonedDateTime
/ java.time.Instant
by interoperability methods, in your particular case GregorianCalendar.toZonedDateTime()
.
在您的特定情况下,大多数旧日历都可以通过互操作性方法轻松转换为java.time.ZonedDateTime
/ 。java.time.Instant
GregorianCalendar.toZonedDateTime()
回答by Basil Bourque
tl;dr
tl;博士
YearWeek.from( // Represents week of standard ISO 8601 defined week-based-year (as opposed to a calendar year).
LocalDate.parse( "2017-01-23" ) // Represents a date-only value, without time-of-day and without time zone.
) // Returns a `YearWeek` object.
.getWeek() // Or, `.getYear()`. Both methods an integer number.
4
4
ISO 8601 standard week
ISO 8601 标准周
If you want the standard ISO 8601 week, rather than a localized definition of a week, use the YearWeek
class found in the ThreeTen-Extraproject that adds functionality to the java.timeclasses built into Java 8 and later.
如果您想要标准的ISO 8601 week,而不是一周的本地化定义,请使用ThreeTen-Extra项目中的YearWeek
类,该项目为 Java 8 及更高版本中内置的java.time类添加了功能。
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
ISO-8601 将一周定义为始终从星期一开始。第一周是包含日历年第一个星期四的那一周。因此,本课程中使用的基于周的年份与日历年不一致。
First, get today's date. The LocalDate
class represents a date-only value without time-of-day and without time zone.
首先,获取今天的日期。该LocalDate
级表示没有时间一天和不同时区的日期,唯一的价值。
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Or let the user specify a date by typing a string. Parsing string input of a date is covered in manyother Questions and Answers. Simplest is to have the user use standard ISO 8601 format, YYYY-MM-DD such as 2017-01-23
.
或者让用户通过键入字符串来指定日期。许多其他问题和答案涵盖了解析日期的字符串输入。最简单的是让用户使用标准的 ISO 8601 格式,YYYY-MM-DD,例如2017-01-23
.
LocalDate ld = LocalDate.parse( "2017-01-23" ) ;
For other formats, specify a DateTimeFormatter
for parsing. Search Stack Overflow for many many examples of using that class.
对于其他格式,请指定 aDateTimeFormatter
进行解析。在 Stack Overflow 中搜索使用该类的许多示例。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( "1/23/2017" , f ) ;
Get the YearWeek
.
获取YearWeek
.
YearWeek yw = YearWeek.from( ld ) ;
To create a string, consider using the standard ISO 8601 format for year-week, yyyy-Www such as 2017-W45
. Or you can extract each number.
要创建字符串,请考虑对 year-week、 yyyy-Www使用标准 ISO 8601 格式,例如2017-W45
. 或者您可以提取每个数字。
YearWeek::getWeek
–?Gets the week-of-week-based-year field.YearWeek::getYear
–?Gets the week-based-year field.
YearWeek::getWeek
–? 获取以周为基础的年字段。YearWeek::getYear
–?获取基于周的年份字段。
Other definitions of week
周的其他定义
The above discussion assumes you go by the ISO 8601 definition of weeksand week-numbering. If instead you want an alternate definition of week and week-numbering, see the Answer by Mobolaji D.using a locale's definition.
上述讨论假设您遵循ISO 8601 对周和周编号的定义。相反,如果您想要周和周编号的替代定义,请参阅Mobolaji D.使用区域设置定义的答案。
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Most of the java.timefunctionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11及更高版本 - 标准 Java API 的一部分,具有捆绑实现。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 大部分java.time功能在ThreeTen-Backport中向后移植到 Java 6 & 7 。
- 安卓
- java.time类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by Sai Gopi N
this one worked for me
这个对我有用
public void sortListItems(List<PostModel> list) {
Collections.sort(list, new Comparator<PostModel>() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
@Override
public int compare(PostModel o1, PostModel o2) {
int ret = 0;
try {
ret = dateFormat.parse(o1.getDate()).compareTo(dateFormat.parse(o2.getDate()));
return ret;
} catch (ParseException e) {
e.printStackTrace();
}
return ret;
}
});
}
回答by Mobolaji D.
WeekFields
WeekFields
This method that I created works for me in Java 8 and later, using WeekFields
, DateTimeFormatter
, LocalDate
, and TemporalField
.
这个方法是我创造了我的作品在Java中8和更高版本,使用WeekFields
,DateTimeFormatter
,LocalDate
,和TemporalField
。
Don't forget to format your date properly based on your use case!
不要忘记根据您的用例正确格式化您的日期!
public int getWeekNum(String input) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yy"); // Define formatting pattern to match your input string.
LocalDate date = LocalDate.parse(input, formatter); // Parse string into a `LocalDate` object.
WeekFields wf = WeekFields.of(Locale.getDefault()) ; // Use week fields appropriate to your locale. People in different places define a week and week-number differently, such as starting on a Monday or a Sunday, and so on.
TemporalField weekNum = wf.weekOfWeekBasedYear(); // Represent the idea of this locale's definition of week number as a `TemporalField`.
int week = Integer.parseInt(String.format("%02d",date.get(weekNum))); // Using that locale's definition of week number, determine the week-number for this particular `LocalDate` value.
return week;
}