DateFormat类的作用:
把时间对象转化成指定格式的字符串。反之,把指定格式的字符串转化成时间对象。DateFormat是一个抽象类,一般使用它的子类SimpleFateFormat类来实现。
DateFormat类和SimpleDateFormat类的使用:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;public class TestDateFormat {public static void main(String[] args){//new 出 SimpleDateFormat 对象SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd");//将时间对象转换成字符串String daytime = s1.format(new Date());System.out.println(daytime);System.out.println(s2.format(new Date()));System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));//将符合指定格式的字符串转成时间对象,字符串格式需要和指定格式一致String time = "2049-10-1";Date date = s2.parse(time);System.out.println("date1:" + date);time = "2049-10-1 20:15:30";date = s1.parse(time);System.out.println("date2:" + date);}
}
代码中的格式化字符的具体含义见表:
| 字母 | 日期或时间元素 | 表示 | 示例 |
| G | Era标识符 | Text | AD |
| y | 年 | Year | 1996;96 |
| M | 年中的月份 | Month | Jujly;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 | 08:00 |
时间格式字符也可以为我们提供其他的便利。比如:获得当前时间是今年的第几天。
获取今天是本年度第几天:
import java.text.SimpleDateFormat;
import java.util.Date;publlic class TestDateFormat2 {SimpleDateFormat s1 = new SimpleDateFormat("D");String daytime = s1.format(new Date());System.out.println(daytime);
}