日期和string相互转换
DateDem.java
package practice; import java.text.ParseException; import java.util.Date; public class DateDemo { /** * 日期和时间相互转换 * @param args */ public static void main(String[] args) throws ParseException { Date d = new Date(); String s1 = DateUtils.dateToString(d,"yyyy年MM月dd日 HH:mm:ss"); System.out.println(s1); System.out.println("------"); String s2 = DateUtils.dateToString(d,"yyyy年MM月dd日"); System.out.println(s2); System.out.println("------"); String s3 = DateUtils.dateToString(d,"HH:mm:ss"); System.out.println(s3); System.out.println("------"); String s = "2022-09-01 17:08:09"; Date dd = DateUtils.stringToDate(s,"yyyy-MM-dd HH:mm:ss"); System.out.println(dd); } }
DateUtils.java
package practice; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 构造方法私有 * 成员方法静态 */ public class DateUtils { private DateUtils(){ } /** * 把日期转为指定格式的字符串 * @params Date date ,String format * @return string */ public static String dateToString(Date date, String format){ SimpleDateFormat sdf = new SimpleDateFormat(); String s = sdf.format(date); return s; } /** * 把字符串转为指定格式的日期 * 返回值类型 Date * 参数:String s,String format */ public static Date stringToDate(String s,String format) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(format); Date d = sdf.parse(s); return d; } }
编译运行:
标签:DateUtils,转换,string,System,Date,date,println,out,String From: https://www.cnblogs.com/yangzailu/p/16647336.html