仅供参考
package com.onecity.comutils;
import com.onecity.usualtemplate.DateCode;
import lombok.Getter;
import lombok.Setter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@Setter
@Getter
public class DateTime extends Date {
private Date datetime;
public DateTime(Date date) {
this.datetime = date;
}
public static DateTime NOW() {
DateTime dt = new DateTime(new Date());
return dt;
}
public static DateTime ShortDate() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String s = sdf.format(new Date());
Date date = sdf.parse(s);
DateTime dt = new DateTime(date);
return dt;
} catch (Exception e) {
return null;
}
}
/**
* 根据日期获取当天是周几
*
* @return 周几
*/
public String dateToWeek() {
String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
Calendar cal = Calendar.getInstance();
try {
cal.setTime(datetime);
} catch (Exception e) {
e.printStackTrace();
}
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) w = 0;
return weekDays[w];
}
public int YEAR() {
Calendar ca = Calendar.getInstance();
ca.setTime(datetime);
return ca.get(Calendar.YEAR);
}
public int MONTH() {
Calendar ca = Calendar.getInstance();
ca.setTime(datetime);
return ca.get(Calendar.MONTH) + 1;
}
public int DAY() {
Calendar ca = Calendar.getInstance();
ca.setTime(datetime);
return ca.get(Calendar.DATE);
}
public int DaysOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
public Date Date() {
return datetime;
}
public DateTime getSunday() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(datetime);
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (day_of_week == 0)
day_of_week = 7;
calendar.add(Calendar.DATE, -day_of_week + 7);
return new DateTime(calendar.getTime());
}
public DateTime adddays(int days) {
Calendar specialDate = Calendar.getInstance();
specialDate.setTime(datetime);
specialDate.add(Calendar.DATE, days);
return new DateTime(specialDate.getTime());
}
public String tostring(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(datetime);
}
public String tostring(DateCode datecode) {
String format = "";
if (datecode == DateCode.YYYY_MM_DD) format = "yyyy-MM-dd";
if (datecode == DateCode.YYYY_MM_DD_HH_MM_SS) format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(datetime);
}
public String todatestring() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(datetime);
}
public static DateTime tryparse(String datestring) {
try {
String formatstring = "";
if (datestring.length() == 10) formatstring = "yyyy-MM-dd";
if (datestring.length() == 19) formatstring = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(formatstring);
Date dt = sdf.parse(datestring);
return new DateTime(dt);
} catch (Exception e) {
return new DateTime(new Date("0000-00-01"));
}
}
}