简体   繁体   English

具有挑战性的Java / Groovy日期操作

[英]Challenging Java/Groovy Date Manipulation

I have a bunch of dates formatted with the year and week, as follows: 我有一堆用年和周格式化的日期,如下所示:

2011-10

The week value is the week of the year(so 1-52). 星期值是一年中的星期(所以是1-52)。 From this week value, I need to output something like the following: 从这个星期的价值,我需要输出类似以下内容:

Mar 7

Explicitly, I need the Month that the given week is in, and the date of the first Monday of that week. 明确地说,我需要给定星期所在的月份,以及该周第一个星期一的日期。 So in other words it is saying that the 10th week of the year is the week of March 7th. 因此,换句话说,每年的第十个星期是3月7日。

I am using Groovy. 我正在使用Groovy。 What kind of date manipulation can I do to get this to work? 为了使它生效,我可以执行哪种日期操作?

Use a GregorianCalendar (or Joda, if you don't mind a dependency) 使用GregorianCalendar(或Joda,如果您不介意依赖项)

    String date = "2011-10";
    String[] parts = date.split("-");
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, Integer.parseInt(parts[0]));
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(parts[1])+1);
    DateFormat df = new SimpleDateFormat("MMM d");
    System.out.println(df.format(cal.getTime()) + " (" + cal.getTime() + ")");

EDIT: Added +1 to week, since calendar uses zero-based week numbers 编辑:由于日历使用从零开始的星期数字,所以增加了+1到星期

You can use SimpleDateFormat , just like in java. 您可以像Java中一样使用SimpleDateFormat See groovyconsole.appspot.com/script/439001 参见groovyconsole.appspot.com/script/439001

java.text.DateFormat df = new java.text.SimpleDateFormat('yyyy-w', new Locale('yourlocale'))
Date date = df.parse('2011-10')

To add a week, simply use Date date = df.parse('2011-10')+7 要添加一周,只需使用Date date = df.parse('2011-10')+7

You don't need to set the Locale if your default Locale is using Monday as the first day of week. 如果您的默认语言环境使用星期一作为一周的第一天,则无需设置语言环境。

Date date = new SimpleDateFormat("yyyy-w", Locale.UK).parse("2011-10");
System.out.println(new SimpleDateFormat("MMM d").format(date));

The first line returns first day of the 10th week in British Locale (March 7th). 第一行返回第10周的第一天(在英国语言环境中)(3月7日)。 When Locale is not enforced, the results are dependent on default JVM Locale . 如果不强制使用Locale ,则结果取决于默认的JVM Locale

Formats are explained here . 格式在这里说明。

Here's a groovy solution: 这是一个时髦的解决方案:

use(groovy.time.TimeCategory) {
    def (y, w) = "2011-10".tokenize("-")
    w = ((w as int) + 1) as String
    def d = Date.parse("yyyy-w", "$y-$w") + 1.day
    println d.format("MMM dd")
}

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

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