我怎样才能在午夜后的几秒钟内获得时间

时间:2015-12-23 07:59:09

标签: java android datetime

这是一个有效的示例代码。如何在Java Android中从午夜开始以秒为单位获取时间

long time = 1450853970
    DateTime.DateFormat = "MM/dd/yyyy"
    long unix_time = DateTime.DateParse(DateTime.Date(time * 1000)) / 1000  
    long time_in_seconds = time - unix_time + (DateTime.TimeZoneOffset * -3600)

2 个答案:

答案 0 :(得分:0)

private int getSecondsFromMidnight(DateTime d) {
    DateTime pastMidnight = d.minusDays(1).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
    Seconds seconds = Seconds.secondsBetween(pastMidnight, d);

    return seconds.getSeconds();
}

答案 1 :(得分:0)

尝试使用Calendar,因为Date很奇怪))

Calendar now = Calendar.getInstance();
Calendar midnight = Calendar.getInstance();

midnight.set(Calendar.HOUR_OF_DAY, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);

long diffeerence  = now.getTimeInMillis() - midnight.getTimeInMillis();`