Java 获取当前时间距离当天凌晨的秒数

在前期项目中遇到一个客户端与服务器间的时间同步问题,需要获取到当前时间与当天凌晨时间距离的秒数,写这篇文章主要是为了总结一下经验提升方便日后温习,以下是具体的测试代码:

Junit的maven依赖

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

具体Java代码

package com.seesun2012.utils.时间;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.junit.Test;

/**
 * 日期时间工具类
 *
 * @author [email protected]
 *
 */
public class DateUtil {

    @Test
    public void sss() throws ParseException{
        long now = System.currentTimeMillis();
        SimpleDateFormat sdfOne = new SimpleDateFormat("yyyy-MM-dd");
        long overTime = (now - (sdfOne.parse(sdfOne.format(now)).getTime()))/1000;
        //当前毫秒数
        System.out.println(now);
        //当前时间  距离当天凌晨  秒数
        System.out.println(overTime);
        //当天凌晨毫秒数
        System.out.println(sdfOne.parse(sdfOne.format(now)).getTime());
        //当天凌晨日期
        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.print(sdfTwo.format(sdfOne.parse(sdfOne.format(now)).getTime()));
    }

}

输出结果

1529576852650       //当前毫秒数
66452               //当前时间  距离当天凌晨  秒数
1529510400000       //当天凌晨毫秒数
2018-06-21 00:00:00 //当天凌晨日期

猜你喜欢

转载自blog.csdn.net/seesun2012/article/details/80764497
今日推荐