Java函数中的时间戳操作技巧
发布时间:2023-06-06 21:06:50
Java中常见的时间戳使用方法是使用System.currentTimeMillis()函数获取当前时间戳,该函数返回的是自1970年1月1日以来的毫秒数。下面介绍一些时间戳操作的技巧。
1. 时间戳转日期
可以使用java.util.Date类将时间戳转换为日期,代码如下:
long timestamp = System.currentTimeMillis(); Date date = new Date(timestamp);
2. 日期转时间戳
可以使用java.util.Date类的getTime()方法将日期转换为时间戳,代码如下:
Date date = new Date(); long timestamp = date.getTime();
3. 时间戳转字符串
可以使用java.text.SimpleDateFormat类将时间戳转换为字符串,代码如下:
long timestamp = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(new Date(timestamp));
上述代码将时间戳转换为格式为“yyyy-MM-dd HH:mm:ss”的字符串。
4. 字符串转时间戳
可以使用java.text.SimpleDateFormat类将字符串转换为时间戳,代码如下:
String dateStr = "2021-01-01 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timestamp = sdf.parse(dateStr).getTime();
上述代码将格式为“yyyy-MM-dd HH:mm:ss”的字符串转换为时间戳。
5. 时间戳加减
可以使用java.util.Calendar类进行时间戳的加减操作,代码如下:
long timestamp = System.currentTimeMillis(); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timestamp); calendar.add(Calendar.HOUR_OF_DAY, 1); // 小时加1 timestamp = calendar.getTimeInMillis();
上述代码将时间戳加上1小时。
6. 时间戳比较
可以使用compareTo()方法比较两个时间戳的大小,代码如下:
long timestamp1 = System.currentTimeMillis(); long timestamp2 = 1609459200000L; // 2021-01-01 00:00:00 的时间戳 int result = Long.compare(timestamp1, timestamp2);
上述代码将当前时间戳和指定的时间戳进行比较,如果当前时间戳比指定时间戳大,则result为1,如果相等则为0,如果小则为-1。
总之,Java中时间戳的基本操作就是转换、计算和比较,通过以上操作技巧,可以更加方便地对时间戳进行处理。
