为一天的开始和结束创建日期时间字符串


create DateTime string for the beginning and the end of the day

如果我有以下字符串:

"2013-10-28"

当我使用以下函数转换为DateTime时:

new 'DateTime("2013-10-28");

它总是给我一个没有设定时间的DateTime

我想有两个日期时间:

  • 一个标记一天的开始,意思是 00:00:00
  • 另一个DateTime在同一天,但在一天结束时 23:59:59

给定上面的字符串,我该如何执行此操作?

Use DateTime::setTime

$d = new 'DateTime("2013-10-28");
$d->setTime(23, 59, 59);

查看所有可能的复合格式。

MySQL 格式对于您的用例来说应该是最简单的:

new 'DateTime("2013-10-28 00:00:00");
new 'DateTime("2013-10-28 23:59:59");

你可以试试这个:

public static Date getDayStartTimeOfTheDate(Date date){
        try {
          Calendar c = Calendar.getInstance();
         c.setTime(date);
         c.set(Calendar.AM_PM, 0);
         c.set(Calendar.HOUR, 0);
         c.set(Calendar.MINUTE, 0);
         c.set(Calendar.SECOND, 0);
         c.set(Calendar.MILLISECOND, 0);
        return parseDate(format(c.getTime()));
      } catch (ParseException e) {
    }
}

对于结束时间,您可以基于上述逻辑编写方法。