1. 說明:
工作中經(jīng)常用到j(luò)ava日期類型Date妻献、Calendar或SimpleDateFormat轿腺,但是這些日期工具類要么提供了過期的方法(Date)向瓷,要么就是功能不夠強(qiáng)大业踢。最近突然用到了Joda-Time日期工具,發(fā)現(xiàn)非常好用嗽冒,就撰寫此文呀伙,以便學(xué)習(xí)和交流。
2. Maven依賴:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.7</version>
</dependency>
3. 實(shí)戰(zhàn):
package com.joda.time.utils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by lance on 2017/3/24.
*/
public class DateTimeFormatterTest {
public static void main(String[] args) {
DateTime dateTime = new DateTime();
System.out.println("currentTimeMillis:" + System.currentTimeMillis());
System.out.println("longDateTime:" + new DateTime().getMillis());
// DateTime換java Date
Date date = dateTime.toDate();
// DateTime換java Calendar
Calendar calendar = dateTime.toCalendar(Locale.CHINESE);
System.out.println("year:" + dateTime.getYear());
System.out.println("month:" + dateTime.getMonthOfYear());
System.out.println("day:" + dateTime.getDayOfMonth());
System.out.println("MinuteOfDay:" + dateTime.getMinuteOfDay());
System.out.println("Hour:" + dateTime.getHourOfDay());
System.out.println("Minute:" + dateTime.getMinuteOfHour());
System.out.println("Second:" + dateTime.getSecondOfMinute());
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy年MM月dd日 HH:mm:ss");
System.out.println(format.print(dateTime.getMillis()));
DateTimeFormatter format1 = DateTimeFormat.forPattern("yyyy.MM.dd HH:mm:ss");
System.out.println(format1.print(dateTime.getMillis()));
DateTimeFormatter format2 = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss");
System.out.println(format2.print(dateTime.getMillis()));
}
}
4.輸出結(jié)果:
currentTimeMillis:1496994136904
longDateTime:1496994136904
year:2017
month:6
day:9
MinuteOfDay:942
Hour:15
Minute:42
Second:16
2017年06月09日 15:42:16
2017.06.09 15:42:16
2017-06-09 03:42:16