首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java:从任何日期获取周数?

Java:从任何日期获取周数?
EN

Stack Overflow用户
提问于 2013-05-07 20:08:10
回答 6查看 107K关注 0票数 11

我有一个小程序,它显示从今天开始的当前星期,如下所示:

代码语言:javascript
复制
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);

然后是一个显示周数字的JLabel:

代码语言:javascript
复制
JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));

所以现在,我希望有一个JTextField,您可以在其中输入日期,JLabel将使用该日期的周数进行更新。我真的不知道该怎么做,因为我对Java还很陌生。我需要将输入保存为字符串吗?一个整数?它必须是什么格式(yyyyMMdd等)?如果有人能帮我的忙,我将不胜感激!

EN

回答 6

Stack Overflow用户

发布于 2016-11-09 03:53:50

Java1.8在java.time包中为您提供了一些新类

代码语言:javascript
复制
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));

大多数遗留日历都可以很容易地通过互操作性方法转换为java.time.ZonedDateTime / java.time.Instant,在您的特定情况下是GregorianCalendar.toZonedDateTime()

票数 15
EN

Stack Overflow用户

发布于 2018-03-21 01:12:25

WeekFields

我使用WeekFieldsDateTimeFormatterLocalDateTemporalField创建的这个方法适用于Java8和更高版本。

别忘了根据你的用例适当地格式化你的日期!

代码语言:javascript
复制
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;
}
票数 5
EN

Stack Overflow用户

发布于 2013-05-07 20:20:34

您可以将日期存储为字符串,并且用户几乎可以以您指定的任何格式输入日期。您只需要使用DateFormat对象来解释它们输入的日期。例如,请参阅Convert String to Calendar Object in Java上的top answer

代码语言:javascript
复制
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"));

要从JTextField中读取日期,您可以将其替换为以下内容:

代码语言:javascript
复制
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // or any other date format
cal.setTime(sdf.parse(dateTextField.getText()));

然后,您只需以问题中显示的相同方式从cal中读取周数。(这是一个简化的示例。您需要处理DateFormat parse方法抛出的潜在ParseException。)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16418661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档