简体   繁体   English

如何从周/年解析为dd / mm / yyyy

[英]How to parse from week/year to dd/mm/yyyy

I'm trying to parse a String that contains week/year information to a normal dd-mm-yyyy format 我正在尝试将包含周/年信息的字符串解析为正常的dd-mm-yyyy格式

import java.util.Calendar;
import java.util.*;
import java.text.*;
import java.util.GregorianCalendar;

public class FromWeektoDate {

public static void main(String[] args) {
    Calendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.setFirstDayOfWeek(Calendar.SUNDAY);
    gregorianCalendar.setMinimalDaysInFirstWeek(4);

     String SemaineYear[] = "20/2018".split("/");


         int s = Integer.parseInt(SemaineYear[0]);
         int a = Integer.parseInt(SemaineYear[1]);
      int numWeekofYear = s;  //INPUT
       int year = a;         //INPUT

    gregorianCalendar.set(Calendar.YEAR , year);
    gregorianCalendar.set(Calendar.WEEK_OF_YEAR , numWeekofYear);

  Date date = new Date();

     date.setDay(gregorianCalendar.get(Calendar.DAY_OF_MONTH) );   
     date.setMonth(gregorianCalendar.get(Calendar.MONTH)  + 1 );
     date.setYear(gregorianCalendar.get
                        (Calendar.YEAR));

    System.out.println(date);
}
}

but I'm getting this error : 但我收到此错误:

 /tmp/java_5kSPR0/FirstDayofWeek.java:26: error: cannot find symbol date.setDay(gregorianCalendar.get(Calendar.DAY_OF_MONTH) ); ^ symbol: method setDay(int) location: variable date of type Date /tmp/java_5kSPR0/FirstDayofWeek.java:27: warning: [deprecation] setMonth(int) in Date has been deprecated 

If you don't care what day within the week you want, you can simply start from New Year's Day and add as many weeks as you like: 如果您不在乎想要在一周中的哪一天,则可以从元旦开始,然后添加任意多的周数:

LocalDate date = LocalDate.of(year, 1, 1).plusWeeks(weekOfYear - 1)

For your example (20th week of 2018), this gives me 2018-05-14 . 例如(2018年第20周),这给了我2018-05-14

java.time java.time

java.time, the modern Java date and time API, can do that. Java.time,现代的Java日期和时间API,可以做到这一点。

    // In Malta weeks begin on Sunday, and there must be at least 4 days
    // of a week in a year for it to be week 1 of that year
    WeekFields wf = WeekFields.of(Locale.forLanguageTag("mt"));

    DateTimeFormatter yearWeekFormatter = new DateTimeFormatterBuilder()
            .appendValue(wf.weekOfWeekBasedYear(), 2)
            .appendLiteral('/')
            .appendValue(wf.weekBasedYear(), 4)
            .parseDefaulting(ChronoField.DAY_OF_WEEK, wf.getFirstDayOfWeek().getValue())
            .toFormatter();

    String weekString = "20/2018";
    LocalDate sundayOfWeek20 = LocalDate.parse(weekString, yearWeekFormatter);
    System.out.println(sundayOfWeek20);

Output from this snippet is: 该代码段的输出为:

2018-05-13 2018-05-13

To format into 13/05/2018 use another DateTimeFormatter : 若要格式化为13/05/2018,请使用另一个DateTimeFormatter

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    System.out.println(sundayOfWeek20.format(dateFormatter));

13/05/2018 13/05/2018

I interpreted from your code that your require a week scheme where the week starts on Sunday and there are at least 4 days in the first week. 我从您的代码中了解到,您需要一个星期计划,其中星期从星期日开始,而第一周至少有4天。 The WeekFields class is used for defining such a scheme. WeekFields类用于定义这种方案。 If your requirement comes out of a specific locale (Malta or Ireland), I recommend using that locale for defining the WeekFields object to use, as I do in the snippet above. 如果您的要求来自特定的语言环境(马耳他或爱尔兰),则我建议使用该语言环境来定义要使用的WeekFields对象,就像在上面的代码段中所做的那样。 If, on the other hand, your requirement doesn't come from some locale, it's better to specify it more directly: 另一方面,如果您的要求不是来自某些区域设置,则最好直接指定它:

    WeekFields wf = WeekFields.of(DayOfWeek.SUNDAY, 4);

I am using java.time's built-in parsing mechanism through LocalDate.parse . 我正在通过LocalDate.parse使用java.time的内置解析机制。 No need to hand parse or otherwise reinvent the wheel. 无需手动解析或以其他方式重新发明轮子。 To have the formatter understand our week scheme I pass TemporalField objects that I get from the WeekFields to DateTimeFormatterBuilder.appenValue . 为了让格式化程序了解我们的周计划,我将从WeekFields获得的TemporalField对象传递给DateTimeFormatterBuilder.appenValue To parse into a LocalDate we need to add a day of week (even though you said you don't care which). 要解析为LocalDate我们需要添加一周中的某一天(即使您说您不在乎哪个)。 I use the call to parseDefaulting for that. 我使用该调用来parseDefaulting

Frankly I was surprised to see how flexible java.time was to meet your requirements. 坦白说,我很惊讶地看到java.time能够满足您的需求。 Even though I knew already that it is a pleasure to work with it. 即使我已经知道与它一起工作是一种乐趣。

The date-time classes that you used — Calendar , GregorianCalendar and Date — are poorly designed and long outdated. 您使用的日期,时间类- CalendarGregorianCalendarDate -的设计不当,早已过时。 I recommend you don't use them. 我建议您不要使用它们。

Link: Oracle tutorial: Date Time explaining how to use java.time. 链接: Oracle教程:Date Time说明如何使用java.time。

Just use getTime to get Date object 只需使用getTime获取Date对象

Date date =  gregorianCalendar.getTime();

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch"). 返回一个Date对象,该对象表示此Calendar的时间值(距纪元的毫秒偏移量)。

Or use SimpleDateFormat for parsing specific format 或使用SimpleDateFormat解析特定格式

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setTimeZone(gregorianCalendar.getTimeZone());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM