1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- package thyyxxk.webserver.utils;
- import java.text.DateFormat;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- public class DateUtil {
- public static String formatPriceTime(String priceTime) {
- return null == priceTime ? "" : priceTime.split("\\.")[0].replace("T", " ");
- }
- public static String formatDatetime(Date date, String pattern) {
- if (null == date) {
- return "";
- }
- SimpleDateFormat sdf = new SimpleDateFormat(pattern);
- return sdf.format(date);
- }
- public static String formatDatetime(Date date) {
- if (null == date) {
- return "";
- }
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- return sdf.format(date);
- }
- public static Date parse(String source) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- try {
- return sdf.parse(source);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return new Date();
- }
- public static long getTimestamp(String datetime) throws ParseException {
- DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- return df.parse(datetime).getTime();
- }
- public static String getOffsetDate(int offset){
- DateFormat da = new SimpleDateFormat("yyyy-MM-dd");
- Calendar now = Calendar.getInstance();
- now.set(Calendar.DATE,now.get(Calendar.DATE) + offset);
- return da.format(now.getTime());
- }
- public static String calculateAge(Date birthDate) {
- if (null == birthDate) {
- return "";
- }
- int age;
- Calendar cal = Calendar.getInstance();
- if (cal.before(birthDate)) {
- throw new IllegalArgumentException("出生日期晚于当前时间,无法计算!");
- }
- int yearNow = cal.get(Calendar.YEAR); //当前年份
- int monthNow = cal.get(Calendar.MONTH); //当前月份
- int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
- cal.setTime(birthDate);
- int yearBirth = cal.get(Calendar.YEAR);
- int monthBirth = cal.get(Calendar.MONTH);
- int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
- age = yearNow - yearBirth; //计算整岁数
- if (monthNow <= monthBirth) {
- if (monthNow == monthBirth) {
- if (dayOfMonthNow < dayOfMonthBirth) {
- // 当前日期在生日之前,年龄减一
- age--;
- }
- } else {
- // 当前月份在生日之前,年龄减一
- age--;
- }
- }
- return String.valueOf(age);
- }
- }
|