1 public static void main(String[] args) throws Exception {
2 // 示例时间戳
3 long hitTime = Long.parseLong("1666627200000");
4 // 将时间戳转换为指定格式的日期字符串
5 String formattedDate = formatDate(hitTime);
6 System.out.println(formattedDate);
7
8 // 将日期字符串转换为时间戳
9 String dateString = "2023-05-05 00:00:00";
10 Long aLong = Date2Long(dateString);
11 System.out.println(aLong);
12 }
13
14 /**
15 * 将时间戳转换为指定格式的日期字符串
16 */
17 public static String formatDate(long hitTime) {
18 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
19 Calendar calendar = Calendar.getInstance();
20 calendar.setTimeInMillis(hitTime);
21 calendar.set(Calendar.HOUR_OF_DAY, 0);
22 calendar.set(Calendar.MINUTE, 0);
23 calendar.set(Calendar.SECOND, 0);
24 calendar.set(Calendar.MILLISECOND, 0);
25 TimeZone timeZone = TimeZone.getDefault();
26 sdf.setTimeZone(timeZone);
27 String format = sdf.format(calendar.getTime());
28 return format;
29 }
30
31 /**
32 * 将日期字符串转换为时间戳
33 */
34 public static Long Date2Long(String dateString) throws ParseException {
35 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
36 Date date = sdf.parse(dateString);
37 long hitTime = date.getTime();
38 return hitTime;
39 }
Long.parseLong("1666627200000") 将字符串 "1666627200000" 转换为 long 类型的时间戳;
formatDate(hitTime) 将时间戳 hitTime 转换为 "yyyy-MM-dd 00:00:00" 格式的日期字符串;
Date2Long(dateString) 将日期字符串 "2023-05-05 00:00:00" 转换为 long 类型的时间戳;
SimpleDateFormat 是 Java 中日期时间格式化的工具类,使用它可以方便地将日期时间字符串转换为日期对象或者将日期对象格式化为指定格式的字符串;
Calendar 是 Java 中的日期时间操作类,通过它可以方便地进行日期时间的加减、设置等操作;
TimeZone 是 Java 中的时区类,可以用来表示不同的时区。在上面的代码中,我们使用了默认时区;
sdf.setTimeZone(timeZone) 将格式化器的时区设置为默认时区,这样在格式化日期时就会按照默认时区进行转换;
parse 方法将字符串转换为日期对象,而 getTime 方法将日期对象转换为毫秒数的时间戳。