Date类: 1、空参数构造方法:获取当前系统的日期和时间 2、Date(long L)传递毫秒值,把毫秒值转换为Date日期 3、GetTime()成员类方法:把日期转换成毫秒 DateFormat类是日期/时间格式化Format子类的抽象类 1、成员方法: (1)String format(Date date)按照指定的模式,把Date日期,格式化为符合模式的字符串 (2)Date parse(String source)把符合模式的字符串,解析为Date日期 2、Dateformat是抽象类,无法直接直接创建对象使用可以使用Dateformat的子类java.text.SimpleDateFormat java.text.SimpleDateFormat extends DateFormat 1、构造方法 SimpleDateFormat(String pattern)用给定的格式和默认语言环境的日期格式符号构造simpleDateFormat 字母 日期或时间元素 表示 示例 G Era 标志符 Text AD y 年 Year 1996; 96 M 年中的月份 Month July; Jul; 07 w 年中的周数 Number 27 W 月份中的周数 Number 2 D 年中的天数 Number 189 d 月份中的天数 Number 10 F 月份中的星期 Number 2 E 星期中的天数 Text Tuesday; Tue a Am/pm 标记 Text PM H 一天中的小时数(0-23) Number 0 k 一天中的小时数(1-24) Number 24 K am/pm 中的小时数(0-11) Number 0 h am/pm 中的小时数(1-12) Number 12 m 小时中的分钟数 Number 30 s 分钟中的秒数 Number 55 S 毫秒数 Number 978 z 时区 General time zone Pacific Standard Time; PST; GMT-08:00 Z 时区 RFC 822 time zone -0800 2、例(日期转换成字符串): //1、创建SimpleDateFormat对象,构造方法中传递指定模式 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //2、调用SimpleDateFormat对象中的方法format,按照构造方法中的指定格式,将Date 日期转换成符合模式的字符串 Date date=new Date();//Date日期 String dtext=sdf.format(date);//将date按照上面的模式转换成字符串 3、例(字符串转换成日期): //1、创建SimpleDateFormat对象,构造方法中传递指定模式 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //2、调用 SimpleDateFormat对象中的parse,把符合构造方法中模式的字符串,解析为Date日期 try { sdf.parse("2022-5-6 12:30:45"); } catch (ParseException e) { e.printStackTrace(); } }
Java日期与字符串转换
最新推荐文章于 2024-05-14 05:17:50 发布