java时间处理

1,951 阅读2分钟

LocalDate类

LocalDate is an immutable datetime class representing a date without a time zone.(LocalDate是一个不可变的datetime类代表一个日期没有一个时区)

LocalDate is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable. (LocalDate是线程安全的和不可改变的,提供的年表。提供所有标准年表类是线程安全的和不可改变的。)

public static DateTimeZone getDefault() {
        DateTimeZone zone = cDefault.get();
        if (zone == null) {
            try {
                try {
                    String id = System.getProperty("user.timezone");
                    if (id != null) {  // null check avoids stack overflow
                        zone = forID(id);
                    }
                } catch (RuntimeException ex) {
                    // ignored
                }
                if (zone == null) {
                    zone = forTimeZone(TimeZone.getDefault());
                }
            } catch (IllegalArgumentException ex) {
                // ignored
            }
            if (zone == null) {
                zone = UTC;
            }
            if (!cDefault.compareAndSet(null, zone)) {
                zone = cDefault.get();
            }
        }
        return zone;
    }

LocalDate转化为int

public static int LocaLDateToInt(LocalDate date) {
		return date.getYear() * 10000 + date.getMonthOfYear() * 100 + date.getDayOfMonth();
	}

LocalDate类

public final class LocalDate
        extends BaseLocal
        implements ReadablePartial, Serializable {
public static DateTime current() {
		return DateTime.now(DateTimeZone.UTC);
	}
//2019-04-12T07:10:14.703Z
DateWork.getAsiaShanghaiTimeZone()

public static DateTimeZone getAsiaShanghaiTimeZone() {
		return DateTimeZone.forID("Asia/Shanghai");
	}


 @FromString
    public static DateTimeZone forID(String id) {
        if (id == null) {
            return getDefault();
        }
        if (id.equals("UTC")) {
            return DateTimeZone.UTC;
        }
        DateTimeZone zone = getProvider().getZone(id);
        if (zone != null) {
            return zone;
        }
        if (id.startsWith("+") || id.startsWith("-")) {
            int offset = parseOffset(id);
            if (offset == 0L) {
                return DateTimeZone.UTC;
            } else {
                id = printOffset(offset);
                return fixedOffsetZone(id, offset);
            }
        }
        throw new IllegalArgumentException("The datetime zone id '" + id + "' is not recognised");
    }
    //Asia/Shanghai
System.out.println(DateUtils.formatToString(DateUtils.current().toDate(), "yyyyMMddHHmm"));

public static String formatToString(Date date, String format) {
		if (date == null) {
			return "";
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(date);
		}
}
//201904121525
public static String formatDate(ReadableInstant instant, String pattern) {
		return DateTimeFormat.forPattern(pattern).print(instant);
}
DateWorks.formatToDate(operateTime, "yyyy-MM-dd HH:mm:ss")
public static Date formatToDate(String dateString, String format) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.parse(dateString);
	}
//返回时区(Asia/Shanghai)
TimeZone timeZone =DateUtils.getAsiaShanghaiTimeZone().toTimeZone();
//
public static int getYear(Date date, TimeZone timeZone) {
		Calendar c = Calendar.getInstance(timeZone);
		c.setTime(date);
		int result = c.get(Calendar.YEAR);
		return result;
}

System.out.println(DateWorks.getYear(DateUtils.current().toDate(), timeZone));
//2019

DateTime中LocalDate()方法日期类型:

 /**
     * Converts this object to a <code>LocalDate</code> with the
     * same date and chronology.
     *
     * @return a LocalDate with the same date and chronology
     * @since 1.3
     */
    public LocalDate toLocalDate() {
        return new LocalDate(getMillis(), getChronology());
    }
    测试:DateTime.now(DateTimeZone.UTC).toLocalDate();
    结果:2019-04-12

DateTime中toLocalDateTime()方法日期类型:

/**
     * Converts this object to a <code>LocalDateTime</code> with
     * the same datetime and chronology.
     *
     * @return a LocalDateTime with the same datetime and chronology
     * @since 1.3
     */
    public LocalDateTime toLocalDateTime() {
        return new LocalDateTime(getMillis(), getChronology());
    }
    
    测试:DateTime.now(DateTimeZone.UTC).toLocalDateTime()
    结果:2019-04-12T08:25:34.576

MutableDateTime类

解释: MutableDateTime is mutable and not thread-safe, unless concurrent threads(MutableDateTime是可变的,而不是线程安全的,除非并发线程不调用mutator方法。)

public class MutableDateTime
        extends BaseDateTime
        implements ReadWritableDateTime, Cloneable, Serializable {

示例

public static LocalDateRangeClass getThisMonth(TimeZone timeZone) {
		DateTimeZone tz = DateTimeZone.forTimeZone(timeZone);//时区Asia/Shanghai
		MutableDateTime mdt = new MutableDateTime(tz);
		mdt.setDayOfMonth(2);//当月的第一天
		resetDayTime(mdt);//
		LocalDate from = mdt.toDateTime().toLocalDate();//2019-04-01
		mdt.addMonths(1);//增加一月
		mdt.setDayOfMonth(1);增加一月的某一天
		resetDayTime(mdt);
		mdt.addMillis(-1);2019-05-01 改变为2019-04-30
		LocalDate to = mdt.toDateTime().toLocalDate();//2019-04-30
		return new LocalDateRangeClass(DateUtils.LocaLDateToInt(from), DateUtils.LocaLDateToInt(to));
		}