DateUtil.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package thyyxxk.webserver.utils;
  2. import java.text.DateFormat;
  3. import java.text.ParseException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Calendar;
  6. import java.util.Date;
  7. public class DateUtil {
  8. public static String formatPriceTime(String priceTime) {
  9. return null == priceTime ? "" : priceTime.split("\\.")[0].replace("T", " ");
  10. }
  11. public static String formatDatetime(Date date, String pattern) {
  12. if (null == date) {
  13. return "";
  14. }
  15. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  16. return sdf.format(date);
  17. }
  18. public static String formatDatetime(Date date) {
  19. if (null == date) {
  20. return "";
  21. }
  22. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  23. return sdf.format(date);
  24. }
  25. public static Date parse(String source) {
  26. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  27. try {
  28. return sdf.parse(source);
  29. } catch (ParseException e) {
  30. e.printStackTrace();
  31. }
  32. return new Date();
  33. }
  34. public static long getTimestamp(String datetime) throws ParseException {
  35. DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  36. return df.parse(datetime).getTime();
  37. }
  38. public static String getOffsetDate(int offset){
  39. DateFormat da = new SimpleDateFormat("yyyy-MM-dd");
  40. Calendar now = Calendar.getInstance();
  41. now.set(Calendar.DATE,now.get(Calendar.DATE) + offset);
  42. return da.format(now.getTime());
  43. }
  44. public static String calculateAge(Date birthDate) {
  45. if (null == birthDate) {
  46. return "";
  47. }
  48. int age;
  49. Calendar cal = Calendar.getInstance();
  50. if (cal.before(birthDate)) {
  51. throw new IllegalArgumentException("出生日期晚于当前时间,无法计算!");
  52. }
  53. int yearNow = cal.get(Calendar.YEAR); //当前年份
  54. int monthNow = cal.get(Calendar.MONTH); //当前月份
  55. int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
  56. cal.setTime(birthDate);
  57. int yearBirth = cal.get(Calendar.YEAR);
  58. int monthBirth = cal.get(Calendar.MONTH);
  59. int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
  60. age = yearNow - yearBirth; //计算整岁数
  61. if (monthNow <= monthBirth) {
  62. if (monthNow == monthBirth) {
  63. if (dayOfMonthNow < dayOfMonthBirth) {
  64. // 当前日期在生日之前,年龄减一
  65. age--;
  66. }
  67. } else {
  68. // 当前月份在生日之前,年龄减一
  69. age--;
  70. }
  71. }
  72. return String.valueOf(age);
  73. }
  74. }