SimpleDateFormat是处理日期格式转换的类。
官方API_1.8关于SimpleDateFormat继承于DateFormate截图:
SimpleDateFormat的构造器如下:
SimpleDateFormat中的格式定义,常用的用红色框圈出:
中文解释:
y : 年
M : 年中的月份
D : 年中的天数
d : 月中的天数
w : 年中的周数
W : 月中的周数
a : 上下/下午
H : 一天中的小时数(0-23)
h : 一天中的小时数(0-12)
m : 小时中的分钟
s : 分钟中的秒数
S : 毫秒数
SimpleDateFormat方法:
继承于DateFormate的方法:
SimpleDateFormat常用方法和常用格式定义使用实例:
package com.lanhuigu.java.format;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class FormatTest {public static void main(String[] args) throws ParseException {// **************1.(format,parse)最常用方法实例************* System.out.println("----------最常用方法---------");// 格式 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 时间 Date date1 = new Date();System.out.println("操作前的时间:" + date1);// 日期类型时间-》转换为定义格式-》字符串类型时间 /* * 注意: format(Date date)这个方法来自于SimpleDateFormat的父类DateFormat */String str1 = sdf1.format(date1);System.out.println("字符串类型时间:" + str1);// 字符串类型时间-》转换为定义格式-》日期类型时间 Date dateF1 = sdf1.parse(str1);System.out.println("日期类型时间:" + dateF1);// **************2.关于常用格式分析************* System.out.println("----------常用格式分析---------");/* * y : 年 * M : 年中的月份 * D : 年中的天数 * d : 月中的天数 * w : 年中的周数 * W : 月中的周数 * a : 上下/下午 * H : 一天中的小时数(0-23) * h : 一天中的小时数(0-12) * m : 小时中的分钟 * s : 分钟钟的秒数 * S : 毫秒数 */// 注意,为了省事,这个地方把常用的都放进来了,一起打印看效果, // 在实际使用中,根据需求进行相应格式转换 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd,w,W,a,HH:mm:ss,SS");String str2 = sdf2.format(new Date());System.out.println("日期类型时间:" + str2);System.out.println("字符串类型时间:" + sdf2.parse(str2));// **************2.关于构造器使用技巧分析************* System.out.println("----------构造器使用技巧分析---------");/* * 构造器: * SimpleDateFormat(); * SimpleDateFormat(String pattern); * SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols); * SimpleDateFormat(String pattern, Locale locale) */// 通过对应构造器构造对象,直接调用方法,简洁写法 System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));}}程序运行结果:
总结
关于SimpleDateFormate需会使用其不同参数下的常用方法,以及常用格式,构造器简写方式。
以上就是本文全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!