Java 时间格式处理

jdk里面的日期格式处理使用SimpleDateFormat,这个类其实也是在内部调用的Calendar

Calendar概念比较负责,涉及到时区和本地化

看一些简单的demo:

package com.qhong;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws Exception {
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        System.out.println(df.format(new Date()));
        Calendar calendar=Calendar.getInstance();
        Date dt=calendar.getTime();
        System.out.println(df.format(dt));
        System.out.println(calendar.getWeekYear());
        System.out.println(calendar.getFirstDayOfWeek());
        System.out.println(calendar.getWeeksInWeekYear());
        System.out.println("====================");
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.println(calendar.get(Calendar.MONTH));
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
        System.out.println("====================");
        System.out.println(calendar.get(Calendar.DATE));
        System.out.println(calendar.get(Calendar.HOUR));
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
        System.out.println(calendar.get(Calendar.MINUTE));
        System.out.println(calendar.get(Calendar.SECOND));
        System.out.println("====================");
        System.out.println(calendar.get(Calendar.MILLISECOND));
        Calendar NewCalendar=Calendar.getInstance();
        NewCalendar.setTime(new Date());
        System.out.println(df.format(NewCalendar.getTime()));
        NewCalendar.add(Calendar.YEAR,-1);
        System.out.println(df.format(NewCalendar.getTime()));
        NewCalendar.add(Calendar.MONTH,2);
        System.out.println(df.format(NewCalendar.getTime()));
        NewCalendar.add(Calendar.DATE,3);
        //后者大,显示 -1  
        System.out.println(df.format(NewCalendar.getTime()));
        System.out.println("时间比较:"+NewCalendar.compareTo(calendar));
        //前者大,显示 1
        NewCalendar.add(Calendar.YEAR,1);
        System.out.println("时间比较:"+NewCalendar.compareTo(calendar));
    }
}
2017-03-13 22:36:08:393
2017-03-13 22:36:08:394
2017
1
52
====================
2017
2
13
2
2
72
====================
13
10
22
36
8
====================
394
2017-03-13 22:36:08:394
2016-03-13 22:36:08:394
2016-05-13 22:36:08:394
2016-05-16 22:36:08:394
时间比较:-1
时间比较:1

比较好的第三方解决方案:joda-time

         <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>

最简单的demo:

package com.qhong;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        
        Date now=new Date();
        DateTime dt=new DateTime(now);
        System.out.println(dt.toString("yyyy-MM-dd HH:mm:ss"));
        String str="2017-08-15 12:12:22";
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        DateTime dt2=format.parseDateTime(str);

        DateTime dt3=DateTime.parse(str,format);
        System.out.println(dt2.equals(dt3));
        System.out.println(dt2.toString("yyyy-MM-dd HH:mm:ss"));

    }
}

Output:

2017-08-06 22:14:15
true
2017-08-15 12:12:22

复杂的demo:

package com.qhong;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {


        //初始化时间
        DateTime dateTime=new DateTime(2017, 8, 6, 20, 34,55);

        //下面就是按照一点的格式输出时间
        String str2 = dateTime.toString("MM/dd/yyyy hh:mm:ss.SSSa");
        String str3 = dateTime.toString("dd-MM-yyyy HH:mm:ss");
        String str4 = dateTime.toString("EEEE dd MMMM, yyyy HH:mm:ssa");
        String str5 = dateTime.toString("MM/dd/yyyy HH:mm ZZZZ");
        String str6 = dateTime.toString("MM/dd/yyyy HH:mm Z");

        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        System.out.println(str5);
        System.out.println(str6);
        System.out.println(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
        System.out.println("==========================");
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        //时间解析
        DateTime dateTime2 = DateTime.parse("2012-12-21 23:22:45", format);

        //时间格式化,输出==> 2012/12/21 23:22:45 Fri
        String string_u = dateTime2.toString("yyyy/MM/dd HH:mm:ss EE");
        System.out.println(string_u);

        //格式化带Locale,输出==> 2012年12月21日 23:22:45 星期五
        String string_c = dateTime2.toString("yyyy年MM月dd日 HH:mm:ss EE", Locale.CHINESE);
        System.out.println(string_c);

        DateTime dt1 = new DateTime();// 取得当前时间

        // 根据指定格式,将时间字符串转换成DateTime对象,这里的格式和上面的输出格式是一样的
        DateTime dt2 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("2012-12-26 03:27:39");

        //计算两个日期间隔的天数
        LocalDate start=new LocalDate(2012, 12,14);
        LocalDate end=new LocalDate(2013, 01, 15);
        int days = Days.daysBetween(start, end).getDays();

        //计算两个日期间隔的小时数,分钟数,秒数

        //增加日期
        DateTime dateTime1 = DateTime.parse("2012-12-03");
        dateTime1 = dateTime1.plusDays(30);
        dateTime1 = dateTime1.plusHours(3);
        dateTime1 = dateTime1.plusMinutes(3);
        dateTime1 = dateTime1.plusMonths(2);
        dateTime1 = dateTime1.plusSeconds(4);
        dateTime1 = dateTime1.plusWeeks(5);
        dateTime1 = dateTime1.plusYears(3);

        // Joda-time 各种操作.....
        dateTime = dateTime.plusDays(1) // 增加天
                .plusYears(1)// 增加年
                .plusMonths(1)// 增加月
                .plusWeeks(1)// 增加星期
                .minusMillis(1)// 减分钟
                .minusHours(1)// 减小时
                .minusSeconds(1);// 减秒数

        //判断是否闰月
        DateTime dt4 = new DateTime();
        org.joda.time.DateTime.Property month = dt4.monthOfYear();
        System.out.println("是否闰月:" + month.isLeap());

        //取得 3秒前的时间
        DateTime dt5 = dateTime1.secondOfMinute().addToCopy(-3);
        dateTime1.getSecondOfMinute();// 得到整分钟后,过的秒钟数
        dateTime1.getSecondOfDay();// 得到整天后,过的秒钟数
        dateTime1.secondOfMinute();// 得到分钟对象,例如做闰年判断等使用

        // DateTime与java.util.Date对象,当前系统TimeMillis转换
        DateTime dt6 = new DateTime(new Date());
        Date date = dateTime1.toDate();
        DateTime dt7 = new DateTime(System.currentTimeMillis());
        dateTime1.getMillis();

        Calendar calendar = Calendar.getInstance();
        dateTime = new DateTime(calendar);
    }
}

Output:

08/06/2017 08:34:55.000下午
06-08-2017 20:34:55
星期日 06 八月, 2017 20:34:55下午
08/06/2017 20:34 Asia/Shanghai
08/06/2017 20:34 +0800
2017-08-06 20:34:55
==========================
2012/12/21 23:22:45 星期五
2012年12月21日 23:22:45 星期五
是否闰月:false

 

比SimpleDataFormat简单多了

http://blog.csdn.net/joyous/article/details/9630893

http://sunnyhl.iteye.com/blog/1205820

http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html

http://ylq365.iteye.com/blog/1769680

posted @ 2017-03-13 22:43  hongdada  阅读(380)  评论(0编辑  收藏  举报