如何使用日历生成开始和结束时间?

时间:2014-09-20 23:23:28

标签: java calendar date-format

我正在尝试使用Calendar获取startTime和endTime,以便我可以相应地创建我的url。我需要将我的startTime设置为昨天午夜2014/09/19 00:00和今天午夜2014/09/20 00:00的结束时间。

所以每当我运行我的程序时,它应该生成我的startTime作为昨天的午夜时间和endTime作为我的程序运行的午夜。

我有以下代码,但如果我现在正在运行我的程序,它将startTime作为2014/09/20 00:00,endTime作为2014/09/20 16:00

private static final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");

Calendar startDate = new GregorianCalendar();
startDate.set(Calendar.MINUTE, 0);
Calendar endDate = (Calendar) startDate.clone();
startDate.set(Calendar.HOUR_OF_DAY, 0);

String startTime = df.format(startDate.getTime());
String endTime = df.format(endDate.getTime());

我在做什么事吗?

2 个答案:

答案 0 :(得分:1)

请尝试以下操作。

    Calendar startDate = new GregorianCalendar();
    startDate.set(Calendar.MINUTE, 0);
    startDate.set(Calendar.HOUR_OF_DAY, 0);
    startDate.add(Calendar.DAY_OF_MONTH, -1);
    String startTime = df.format(startDate.getTime());
    System.err.println(startTime);

    Calendar endDate = (Calendar) startDate.clone();
    endDate.add(Calendar.DAY_OF_MONTH, 1);
    String endTime = df.format(endDate.getTime());
    System.err.println(endTime);

它应该完成这项工作(2014/09/21 01:50 AM):

2014/09/20 00:00
2014/09/21 00:00

答案 1 :(得分:0)

Day并不总是在00:00:00

开始

问题和其他答案都假设当天的第一时刻("午夜")是00:00:00.000的时间。由于夏令时和可能的其他异常情况,并非总是如此。

时区

问题和其他答案都忽略了时区问题。确定日期取决于时区。通常最好明确指定预期的时区。

约达时间

以下是一些使用Joda-Time 2.4库来回答问题的示例代码,同时解决了上面列出的两个问题。

DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( timeZone );
DateTime todayStart = now.withTimeAtStartOfDay();
DateTime tomorrowStart = now.plusDays( 1 ).withTimeAtStartOfDay();

Plus Joda-Time有三个类来代表一段时间:Interval,Period和Duration。

Interval today = new Interval( todayStart, tomorrowStart );
相关问题