时间类型转换——date和String的相互转换

  • Post author:
  • Post category:其他


经常性在代码中需要做一些时间处理,有的时候一着急就会写错,特此总结一下

public static void main(String[] args) {
        String ds = "20220923";
        String ds1 = "2022-10-18T02:36:34.000Z";
        Long millisDate = 1663948799000l;
        Long times = 1663948799l;

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        try {
            //UTC格式转date
            Date parse1 = sdf1.parse(ds1);

            //字符串String转date
            Date parse = format.parse(ds + " 00:00:00");

            //字符串转date获取毫秒值
            long time = format.parse(ds + " 23:59:59").getTime();

            //date转String
            String formatTime = sdf.format(parse);

            //date转String
            String formatTime1 = simpleDateFormat.format(new Date());

            //毫秒转年月日时分秒
            String millisStr = sdf.format(millisDate);

            //秒级时间戳转年月日时分秒
            String timeStr = sdf.format(new Date(times*1000L));

            System.out.println("parse1:"+parse1); //Fri Sep 23 00:00:00 CST 2022
            System.out.println("date:"+parse); //Fri Sep 23 00:00:00 CST 2022
            System.out.println("millisecond:"+time); //1663948799000
            System.out.println("String time:"+formatTime); //2022-09-23 00:00:00
            System.out.println("formatTime1:"+formatTime1);  //20230227134002
            System.out.println("millisStr:"+ millisStr); //2022-09-23 23:59:59
            System.out.println("timeStr:"+ timeStr); //2022-09-23 23:59:59

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


重点还是date转String用format,String转date用parse

拓展知识,急于使用的可忽略以下内容。

我们可以来分析一波源码。

首先看parse,也就是字符串转日期。该方法为分析给定字符串开头的文本以生成日期。

public Date parse(String source) throws ParseException
    {
        ParsePosition pos = new ParsePosition(0);
        //source为需要解析的字符串,pos为解析开始的位置
        //pos输出为解析终止的位置。如果解析失败,则会返回到开始位置
        Date result = parse(source, pos);
        //根据pos的index判断是否解析成功
        if (pos.index == 0)
            throw new ParseException("Unparseable date: \"" + source + "\"" ,
                pos.errorIndex);
        return result;
    }

再看format方法。将日期格式化为日期/时间字符串。

date为要格式化为时间字符串的时间值。

通过源码也可以到看到,format是将时间进行比较,从而进行字符串的拼接,最终形成日期字符串返回。

    public final String format(Date date)
    {
        return format(date, new StringBuffer(),
                      DontCareFieldPosition.INSTANCE).toString();
    }


    public abstract StringBuffer format(Date date, StringBuffer toAppendTo,
                                        FieldPosition fieldPosition);

    //找了AbsoluteTimeDateFormat的format来看一下
    public StringBuffer format(Date date, StringBuffer sbuf, FieldPosition fieldPosition) {
        long now = date.getTime();
        int millis = (int)(now % 1000L);
        if (now - (long)millis == previousTime && previousTimeWithoutMillis[0] != 0) {
            sbuf.append(previousTimeWithoutMillis);
        } else {
            this.calendar.setTime(date);
            int start = sbuf.length();
            int hour = this.calendar.get(11);
            if (hour < 10) {
                sbuf.append('0');
            }

            sbuf.append(hour);
            sbuf.append(':');
            int mins = this.calendar.get(12);
            if (mins < 10) {
                sbuf.append('0');
            }

            sbuf.append(mins);
            sbuf.append(':');
            int secs = this.calendar.get(13);
            if (secs < 10) {
                sbuf.append('0');
            }

            sbuf.append(secs);
            sbuf.append(',');
            sbuf.getChars(start, sbuf.length(), previousTimeWithoutMillis, 0);
            previousTime = now - (long)millis;
        }

        if (millis < 100) {
            sbuf.append('0');
        }

        if (millis < 10) {
            sbuf.append('0');
        }

        sbuf.append(millis);
        return sbuf;
    }



版权声明:本文为Aguai229原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。