- 在 Java 应用中,格式化日期时间通常会用到 SimpleDateFormat 类
- public class SimpleDateFormat extends DateFormat
- SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类。 它允许格式 化 (date -> text)、语法分析 (text -> date)和标准化。
- SimpleDateFormat 允 许以为日期-时间格式化选择任何用户指定的方式启动。 但是,希望 用 DateFormat 中的 getTimeInstance、 getDateInstance 或 getDateTimeInstance 创 建一个日期-时间格式化程序。 每个类方法返回一个以缺省格式化方式初始化的日期/时间格式化程序。 可以根据需要用 applyPattern 方法修 改格式化方式。
- SimpleDateFormat 函数的继承关系:
- java.lang.Object
- |
- ----java.text.Format
- |
- ----java.text.DateFormat
- |
- ----java.text.SimpleDateFormat
- 下面是个小例子:
- import java.text.*;
- import java.util.Date;
- /**
- SimpleDateFormat 函数语法:
- G 年代标志符
- y 年
- M 月
- d 日
- h 时 在上午或下 午 (1~12)
- H 时 在一天 中 (0~23)
- m 分
- s 秒
- S 毫秒
- E 星期
- D 一年中的第几天
- F 一月中第几个星期几
- w 一年中第几个星期
- W 一月中第几个星期
- a 上午 / 下午 标 记符
- k 时 在一天 中 (1~24)
- K 时 在上午或下 午 (0~11)
- z 时区
- */
- public class FormatDateTime {
- public static void main(String[] args) {
- SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
- SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");
- SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()
- SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
- SimpleDateFormat myFmt4=new SimpleDateFormat(
- "一年中的第 D 天 一年中第w个星期 一月中第W个星期 在一天中k时 z时区");
- Date now=new Date();