我有一个小程序,它显示从今天开始的当前星期,如下所示:
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);
然后是一个显示周数字的JLabel:
JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));
所以现在,我希望有一个JTextField,您可以在其中输入日期,JLabel将使用该日期的周数进行更新。我真的不知道该怎么做,因为我对Java还很陌生。我需要将输入保存为字符串吗?一个整数?它必须是什么格式(yyyyMMdd等)?如果有人能帮我的忙,我将不胜感激!
发布于 2016-11-09 03:53:50
Java1.8在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));
大多数遗留日历都可以很容易地通过互操作性方法转换为java.time.ZonedDateTime
/ java.time.Instant
,在您的特定情况下是GregorianCalendar.toZonedDateTime()
。
发布于 2018-03-21 01:12:25
WeekFields
我使用WeekFields
、DateTimeFormatter
、LocalDate
和TemporalField
创建的这个方法适用于Java8和更高版本。
别忘了根据你的用例适当地格式化你的日期!
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;
}
发布于 2013-05-07 20:20:34
您可以将日期存储为字符串,并且用户几乎可以以您指定的任何格式输入日期。您只需要使用DateFormat
对象来解释它们输入的日期。例如,请参阅Convert String to Calendar Object in Java上的top answer。
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
中读取日期,您可以将其替换为以下内容:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // or any other date format
cal.setTime(sdf.parse(dateTextField.getText()));
然后,您只需以问题中显示的相同方式从cal
中读取周数。(这是一个简化的示例。您需要处理DateFormat
parse
方法抛出的潜在ParseException
。)
https://stackoverflow.com/questions/16418661
复制相似问题