2

我正在尝试在每个星期日的午夜运行一份报告,其中将包括从上一个星期六午夜到报告开始前的 11:59:59 的数据。因此,如果要在即将到来的星期日(2/17)开始,它将:

  • 在 2013 年 2 月 17 日午夜执行(或星期一早上,但你想怎么想)
  • 包括从 2/10/2013 12:00:00 AM(上周六午夜)开始的数据
  • 包括截至 2013 年 2 月 16 日晚上 11:59:59 的数据(本周六晚上,报告触发前 1 秒)

我正在尝试获取startDateTimeendDateTime封装时间范围,并希望使用 JODALocalDateTime来保存每个值。然后我需要将它们格式化为 YYYYMMDD_HHmmss 格式的字符串。

这是我最好的尝试:

LocalDateTime rightNow = new LocalDateTime();
LocalDateTime startDateTime = rightNow.minusDays(7);
LocalDateTime endDateTime = rightNow.minusDays(1);

String startDateTimeFormatted = startDateTime.toString();
String endDateTimeFormatted = endDateTime.toString();

System.out.println(startDateTimeFormatted);
System.out.println(endDateTimeFormatted);

当我运行它时,我得到:

2013-02-06T12:10:27.411
2013-02-12T12:10:27.411

注意:由于我今天(2013 年 2 月 13 日)运行此代码,因此开始/结束日期不同,它们将在 2/17 星期日(或任何其他星期日),但它的时间表示和字符串格式我'我真的对这里很感兴趣。

所以我问:

  1. 如何startDateTime表示(对于这个例子 - 但我需要动态的答案!) 2/10/2013 12:00:00 AM
  2. 如何endDateTime表示(对于这个例子 - 但我需要答案是动态的!) 2/16/2013 11:59:59 PM
  3. 如何格式化startDateTimeendDateTime分别显示为 20130210_120000 和 20130216_115959?

提前致谢。

4

2 回答 2

6

好的,如前所述,我强烈建议使用 UTC 作为时区,并作为唯一的终点。因此,您可以使用:

private static final DateTimeFormatter FORMATTER =
    DateTimeFormat.forPattern("yyyyMMdd'_'HHmmss")
                  .withLocale(Locale.US);
...

// I prefer to be explicit about using "the current time". I prefer to use
// an injectable dependency such as a Clock type, too...
DateTime now = new DateTime(System.currentTimeMillis(), DateTimeZone.UTC);

// Note: this *doesn't* ensure that it's the right day of the week.
// You'd need to think about that separately - it may be as simple as
// scheduling it appropriately... but bear your local time zone in mind!
DateTime end = now.withTimeAtStartOfDay();
DateTime start = end.minusDays(7);

String startText = FORMAT.print(start);
String endText = FORMAT.print(end);

进一步注意,这将使用 24 小时制,因此它会给出20130210_00000020130217_000000不是120000用作时间。这是更加一致和明确的。鉴于它总是午夜,您可能只想完全使用yyyyMMdd和删除时间部分。

于 2013-02-13T17:56:54.467 回答
1

System.out.println(DateTime.now().toString("yyyy-MM-dd"));

toString 方法接受格式化模板,请参阅:http: //joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html

于 2013-02-13T17:30:09.077 回答