一、时间戳
时间戳是指英国大伦敦格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数
二、java时间格式化字母及其含义
| 字母 | 含义 |
|---|---|
| G | Era 标志符 |
| y | 年 |
| M | 年中的月份 |
| w | 年中的周数 |
| W | 月中的周数 |
| D | 年中的天数 |
| d | 月份中的天数 |
| F | 月份中的星期 |
| E | 星期中的天数 |
| a | am/pm 标记 |
| H | 一天中的小时数(0-23) |
| k | 一天中的小时数(1-24 |
| K | am/pm 中的小时数(0-11) |
| h | am/pm 中的小时数(1-12) |
| m | 小时中的分钟数 |
| s | 分钟中的秒数 |
| S | 毫秒数 |
| z | 时区 |
| Z | 时区 |
三、代码展示
- 时间对象格式化为字符串 .format()方法
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate {
public static void main(String[] args) {
//获取当前时间戳 (毫秒)
Long currentTime = System.currentTimeMillis();
System.out.println("当前时间戳为: " + currentTime);
Date date = new Date(currentTime);
System.out.println("当前时间戳转换成时间为: " + date);
// 定义格式化时间输出格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentSimpleDateFormat = simpleDateFormat.format(date);
System.out.println("当前时间戳转换成时间格式化后为: " + currentSimpleDateFormat);
}
}
- 字符串时间格式化为时间对象 .parse()方法
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate {
public static void main(String[] args) {
// 定义字符串日期
String strDate = "2020-02-02";
// 初始化格式化时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
// 解析字符串时间,转换成 Date 类型
Date date = simpleDateFormat.parse(strDate);
System.out.println("字符串时间转换成时间为: " + date);
// 将时间转换成时间戳
Long longDate = date.getTime();
System.out.println("时间转换成时间戳为: " + longDate);
// 将时间格式化输出
String strSimpleDateFormat = simpleDateFormat.format(date);
System.out.println("时间格式化输出为: " + strSimpleDateFormat);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
本文介绍了Java中时间戳的概念,详细讲解了Java时间格式化的字母含义,并通过实例展示了如何使用.format()方法将时间对象格式化为字符串,以及使用.parse()方法将字符串转换为时间对象。
1135

被折叠的 条评论
为什么被折叠?



