This article has shared the specific code of the DateUtils time tool class for your reference. The specific content is as follows
package com.example.administrator.myapp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Date tool class* Created by lychun on 2017/12/07. */ public class DateUtils { /** * Get a few days ago* * @param d Time* @param day How many days* @return result*/ public static Date getDateBefore(Date d, int day) { Calendar now = Calendar.getInstance(); now.setTime(d); now.set(Calendar.DATE, now.get(Calendar.DATE) - day); return now.getTime(); } /** * Get the time after a few days* * @param d Time* @param day How many days* @return result*/ public static Date getDateAfter(Date d, int day) { Calendar now = Calendar.getInstance(); now.setTime(d); now.set(Calendar.DATE, now.get(Calendar.DATE) + day); return now.getTime(); } /** * Get the current timestamp (exact to seconds) */ public static String getCurrTimeStamp() { long time = System.currentTimeMillis(); String t = String.valueOf(time / 1000); return t; } /** * Convert the date format string to a timestamp* * @param date_str String date* @param format For example: yyyy-MM-dd HH:mm:ss * @return */ public static String date2TimeStamp(String date_str, String format) { try { SimpleDateFormat sdf = new SimpleDateFormat(format); return String.valueOf(sdf.parse(date_str).getTime() / 1000); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * Date Convert to timestamp* @param date Time* @return */ public static String dateTimeStamp(Date date) { return String.valueOf(date.getTime() / 1000); } /** * Convert String to Date * * @param str String * @param format Format * @return Result */ public static Date stringToDate(String str, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format);// lowercase mm represents minutes Date date = null; try { date = sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); } return date; } //Convert String to Date public static Date stringToDate(String str) { return stringToDate(str, "yyyy-MM-dd"); } /** * Convert Date to String * * @param date Time* @param format Converted format* @return result*/ public static String dateToString(Date date, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); String result = sdf.format(date); return result; } //Convert time to year-month-day format public static String dateToString(Date date) { return dateToString(date, "yyyy-MM-dd"); } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.