fxleyu / cu-cafes

This is a repository of Java. And CU is a cafes unders downstairs.
2 stars 0 forks source link

[基础][细节] 关于 Java 中日期与时间戳的思考 #62

Closed fxleyu closed 6 years ago

fxleyu commented 6 years ago

现在想到的问题如下:

fxleyu commented 6 years ago

离第二天凌晨的毫秒数

private static final int OFFSET = Calendar.getInstance().getTimeZone().getRawOffset();
private static final long MS_OF_DAY = 1000 * 60 * 60 * 24;
long millisOfToday = (System.currentTimeMillis() + OFFSET) % MS_OF_DAY;
fxleyu commented 6 years ago

日期文本解析为 Date 对象


long startTime = TimeUtils.getTimeFromYMDHMSDate(startTimeStr).getTime();
private static final String yearMonthDayHourMiunitSecondFormat = "yyyy-MM-dd HH:mm:ss";
private static final HashMap<String, ThreadLocal<SimpleDateFormat>> formatHashMap = new HashMap<String, ThreadLocal<SimpleDateFormat>>();

    public static Date getTimeFromYMDHMSDate(String strTime) {
        return getSdf(yearMonthDayHourMiunitSecondFormat).parse(strTime, new ParsePosition(0));
    }
    private static SimpleDateFormat getSdf(final String pattern) {
        ThreadLocal<SimpleDateFormat> sdfThreadLocal = formatHashMap.get(pattern);
        if (sdfThreadLocal==null) {
            synchronized (lockObj) {
                sdfThreadLocal = formatHashMap.get(pattern);
                if (sdfThreadLocal==null) {
                    sdfThreadLocal = new ThreadLocal<SimpleDateFormat>(){
                        @Override
                        protected SimpleDateFormat initialValue() {
                            return new SimpleDateFormat(pattern);
                        }
                    };
                    formatHashMap.put(pattern, sdfThreadLocal);
                }
            }
        }
        return sdfThreadLocal.get();