Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java TimeUnit 类 #58

Open
techiall opened this issue Jul 12, 2019 · 0 comments
Open

Java TimeUnit 类 #58

techiall opened this issue Jul 12, 2019 · 0 comments
Labels

Comments

@techiall
Copy link
Owner

获得当前日期凌晨的时间戳

Java 中的 Date 类,已经不推荐使用了,现在使用 Calendar 类,他可以转换成 Date ,通过 .getTime() 方法返回一个 Date

    /**
     * @return 返回当日零点时间戳
     */
    public static long getTodayZeroTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(
            calendar.get(Calendar.YEAR), 
            calendar.get(Calendar.MONTH), 
            calendar.get(Calendar.DATE),
            0, 0, 0
        );
        return calendar.getTimeInMillis();
    }

Calendar 通过 getInstance() 方法获得一个当前时间的对象;通过 set 方法可以设置你所需要的时间;get 方法可获得时间对应字段的值。getTimeInMillis() 返回毫秒精度的时间戳。

一天有多少秒

有人说这还不简单,直接 60 * 60 * 24 ,60 秒 * 60 分钟 * 24 小时,不就是答案了。

private static final int ONE_DAY = 60 * 60 * 24;

这样子确实可以,但是没那么直观吧,我们可以通过使用 TimeUnit 类。

private static final long ONE_DAY = TimeUnit.DAYS.toSeconds(1);

是不是比上面简洁和明白多了,它的意思就是将 1 DAYA 转换成 Secondes。

TimeUnit 类有很多方法,可以用于时间转换。

Spring Boot Utils 类

写代码过程中,总会用到一些工具类,自己封装的或者别人写的,再封装一层。

如封装了一个 TimeUtils 类,用于和时间相关的操作,提供静态方法。那我们可以通过 @Component 进行注入。

但是我更加喜欢以下写法,不加 @Component 注解,并私有构造方法,如果构造了就抛异常。

但是如果加了 @Component 方法,又私有了构造函数,会抛异常,因为注入失败。

import java.util.Calendar;

/**
 * @author techial
 */
public class TimeUtils {
    private TimeUtils() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * @return 返回当日零点时间戳
     */
    public static long getTodayZeroTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE),
            0, 0, 0
        );
        return calendar.getTimeInMillis();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant