Java 8 中对时间的处理提供了新的API
对日期时间的处理在实际的开发中是很常见的需要,Java中对时间的处理一直备受诟病。现在这一问题,在新版本的java 8 中,终于有了新的改变。详见Demo。
public class Java8_Date {
// java8新特性
public static void main(String args[]){
// 获取当前日期
LocalDate today = LocalDate.now();
System.out.println("Today's Local date : " + today);
// 获取年月日
today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.printf("Year : %d Month : %d day : %d %n", year, month, day);
// 以前的api,Calendar获取本地时区的实例
// Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
//
// Date currentTime = localCalendar.getTime();
// int currentDay = localCalendar.get(Calendar.DATE);
// int currentMonth = localCalendar.get(Calendar.MONTH) + 1;
// int currentYear = localCalendar.get(Calendar.YEAR);
// int currentDayOfWeek = localCalendar.get(Calendar.DAY_OF_WEEK);
// int currentDayOfMonth = localCalendar.get(Calendar.DAY_OF_MONTH);
// int CurrentDayOfYear = localCalendar.get(Calendar.DAY_OF_YEAR);
//
// System.out.println("Current Date and time details in local timezone");
// System.out.println("Current Date: " + currentTime);
// System.out.println("Current Day: " + currentDay);
// System.out.println("Current Month: " + currentMonth);
// System.out.println("Current Year: " + currentYear);
// System.out.println("Current Day of Week: " + currentDayOfWeek);
// System.out.println("Current Day of Month: " + currentDayOfMonth);
// System.out.println("Current Day of Year: " + CurrentDayOfYear);
// 处理具体日期
LocalDate dateOfBirth0 = LocalDate.of(2010, 01, 14);
System.out.println("Your Date of birth is : " + dateOfBirth0);
// 判断两个日期是否相等
LocalDate date1 = LocalDate.of(2014, 01, 14);
if(date1.equals(today)){
System.out.printf("Today %s and date1 %s are same date %n", today, date1);
}
// 判断周期性日期大小
LocalDate dateOfBirth = LocalDate.of(2010, 10, 14);
MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(today);
if(currentMonthDay.equals(birthday)){
System.out.println("Many Many happy returns of the day !!");
}else{
System.out.println("Sorry, today is not your birthday");
}
if(currentMonthDay.isBefore(birthday)){
System.out.println("你今年的生日还没过!");
}else {
System.out.println("你今年的生日已过!");
}
// 获取当前时间
LocalTime time = LocalTime.now();
System.out.println("local time now : " + time);
LocalTime time0 = LocalTime.now();
LocalTime newTime = time0.plusHours(2); // adding two hours
System.out.println("两个小时之后 : " + newTime);
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("今天是 : " + today);
System.out.println("一周之后 : " + nextWeek);
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
System.out.println("一年之前 : " + previousYear);
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("一年之后 : " + nextYear);
// Returns the current time based on your system clock and set to UTC.
Clock clock = Clock.systemUTC();
System.out.println("Clock : " + clock);
System.out.println("格林尼治时间:" + LocalDate.now(clock) + " " + LocalTime.now(clock));
// Returns time based on system clock zone
Clock defaultClock = Clock.systemDefaultZone();
System.out.println("Clock : " + defaultClock);
System.out.println("北京时间:" + LocalDateTime.now(defaultClock));
// Date and time with timezone in Java 8
ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
YearMonth creditCardExpiry = YearMonth.of(2018, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
// 是否是闰年
if(today.isLeapYear()){
System.out.println("This year is Leap year");
}else {
System.out.println("This year is not a Leap year");
}
// 计算两个日期之间的天数和月数
LocalDate java8Release = LocalDate.of(2016, Month.MAY, 14);
Period periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : "
+ periodToNextJavaRelease.getMonths() );
// 包含时差信息的日期和时间
LocalDateTime datetime = LocalDateTime.of(2014, Month.JANUARY, 14, 19, 30);
ZoneOffset offset = ZoneOffset.of("+05:30");
OffsetDateTime date = OffsetDateTime.of(datetime, offset);
System.out.println("Date and Time with timezone offset in Java : " + date);
// 在Java 8中获取当前的时间戳
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp);
// 在Java 8中如何使用预定义的格式化工具去解析或格式化日期
String dayAfterTommorrow = "20140116";
LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
DateTimeFormatter.BASIC_ISO_DATE);
System.out.printf("Date generated from String %s is %s %n",
dayAfterTommorrow, formatted);
// 如何在Java中使用自定义格式化工具解析日期
String goodFriday = "Nov 13 2015";
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy");
LocalDate holiday = LocalDate.parse(goodFriday, formatter);
System.out.printf("Successfully parsed String %s, date is %s%n", goodFriday, holiday);
} catch (DateTimeParseException ex) {
System.out.printf("%s is not parsable!%n", goodFriday);
ex.printStackTrace();
}
// 在Java 8中如何把日期转换成字符串
LocalDateTime arrivalDate = LocalDateTime.now();
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm a");
String landing = arrivalDate.format(format);
System.out.printf("Arriving at : %s %n", landing);
} catch (DateTimeException ex) {
System.out.printf("%s can't be formatted!%n", arrivalDate);
ex.printStackTrace();
}
}
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TimeDemo {
public static void main(String args[]) throws Exception{
// System.out.println(DateUtil.getSystemCurrentTimeFormat(DateUtil.getSystemCurrentDate(), "yyyy/MM/dd HH:mm:ss"));
// System.out.println(DateUtil.parseDateStringToDate("2013/12/15 12:58:20", "yyyy/MM/dd HH:mm:ss"));
// System.out.println(DateUtil.getCurrentYear());
System.out.println(DateUtil.getCountdownValue(380*24*60*60*1000l));
}
static class DateUtil{
/**
* 获取当前系统的时间
* @return 当前的Date对象
*/
public static Date getSystemCurrentDate(){
return new Date();
}
public static int getCurrentYear(){
Calendar date = Calendar.getInstance();
return date.get(Calendar.YEAR);
}
/**
* 获取当前系统的时间的毫秒值,自1970-1-1 00:00:00开始的毫秒值
* @return 当前的Date对象的毫秒值
*/
public static long getSystemCurrentTimeLong(){
return getSystemCurrentDate().getTime();
}
/**
* 根据给定的pattern,返回格式化后的Date
* @param date Date对象
* @param pattern 格式化模式
* @return 格式化后的时间字符串
*/
public static String getSystemCurrentTimeFormat(Date date, String pattern){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
/**
* 将格式化后的时间字符串解析成Date对象
* @param dateString 格式化后的String时间类型,如"2013/12/15 12:58:20"
* @param pattern 格式化用的模式String 如"yyyy/MM/dd HH:mm:ss"
* @return 返回Date对象
* @throws ParseException 转换异常
*/
private static Date parseDateStringToDate(String dateString, String pattern) throws ParseException {
DateFormat df = new SimpleDateFormat(pattern);
Date date = df.parse(dateString);
return date;
}
public static final String COUNTDOWN_YEAR = "countdown_year";
public static final String COUNTDOWN_MONTH = "countdown_month";
public static final String COUNTDOWN_WEEK = "countdown_week";
public static final String COUNTDOWN_DAY = "countdown_day";
public static final String COUNTDOWN_HOUR = "countdown_hour";
public static final String COUNTDOWN_MINUTE = "countdown_minute";
public static final String COUNTDOWN_SECOND = "countdown_second";
/**
* 通过倒计时毫秒值,计算倒计时结果
* @param countdown 倒计时毫秒值
* @return 结果集合
*/
private static Map<String, Integer> getCountdownValue(long countdown){
if(countdown < 0){
throw new NumberFormatException("countdown time should not be less than zero!");
}
int yearDays, remainingTime;
if(isLeapYear(getCurrentYear())){
yearDays = 366;
}else {
yearDays = 365;
}
// 总剩余时间距今还有多少个星期
int week = (int) (countdown / 7*24*60*60*1000);
// 总剩余时间距今还有多少年
int year = (int) (countdown/(yearDays*24*60*60*1000));
// 刨去年数,剩余时间距今还有多少月、或者多少天(通常的说法:1年零6个月、1年零123天)
remainingTime = (int) (countdown%(yearDays*24*60*60*1000));
int day = remainingTime / 24*60*60*1000;
int month = getMonthIntervalAfterDays(day);
remainingTime = remainingTime % 24*60*60*1000;
// 余下的时间求时分秒
int hour = remainingTime / 60*60*1000;
remainingTime = remainingTime % 60*60*1000;
int minute = remainingTime / 60*1000;
remainingTime = remainingTime % 60*60*1000;
int second = remainingTime / 1000;
Map<String, Integer> resultMap = new HashMap<String, Integer>();
resultMap.put(COUNTDOWN_WEEK, week);
resultMap.put(COUNTDOWN_YEAR, year);
resultMap.put(COUNTDOWN_MONTH,month);
resultMap.put(COUNTDOWN_DAY, day);
resultMap.put(COUNTDOWN_HOUR, hour);
resultMap.put(COUNTDOWN_MINUTE, minute);
resultMap.put(COUNTDOWN_SECOND, second);
return resultMap;
}
/**
* 判断是否是闰年
* @param year 给定的年
* @return
*/
public static boolean isLeapYear(int year){
if(year % 4 == 0 && year % 100 != 0 ||
year % 400 == 0){
return true;
}else{
return false;
}
}
/**
* 以当下时间为基准,给定天数后距今相差几个月
* @param d 给定的天数
* @return 相差的天数
*/
public static int getMonthIntervalAfterDays(int d){
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date2.add(Calendar.DAY_OF_MONTH, d);
return date2.get(Calendar.MONTH) - date1.get(Calendar.MONTH);
}
}
}