实现将时间戳转换为指定格式日期js 时间戳转换成时间
当从Kafka服务器获取数据的时候,有时候获取的数据中的时间在很多的情况下是时间戳,类似于1638410263503这样的长整型。当然,我们不可能将这些数据以时间戳的形式展示给用户。通常情况,是要对这个时间戳进行处理加工,使其变成我们想要并习惯浏览的那种格式。

那么怎么处理这些时间戳格式的数据呢?在Java中,可以参考如下示例代码来实现。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* 将时间戳转换为指定格式日期
*
*/
public class App
{
public static void main( String[] args )
{
// 获取当前时间戳 -- 如 1638410263503, 1638275127201
long timestamp1 = System.currentTimeMillis();
System.out.println("时间戳:" + timestamp1);
System.out.println(timestamp2Date(timestamp1, ""));
}
public static String timestamp2Date(long timestamp, String format){
if(format == null || format.length()<=0) {
format = "yyyy-MM-dd HH:mm:ss";
}
return new SimpleDateFormat(format, Locale.CHINA).format(new Date(timestamp));
}
}
运行结果如下图所示:

需要注意一点,上述时间戳数据在MySQL中通过 from_unixtime()函数进行格式转换时,需要除以1000。
在我们实际中用的时间戳一般都是十三位的时间戳,精确到毫秒了,如果将精确到毫秒的时间戳输入方法中会有错误,出现错误的日期。from_unixtime的输入单位是秒,也就是十位的BIGINT。
mysql> select from_unixtime(1638275127201/1000);

from_unxitime语法说明:
from_unixtime(unix_timestamp, format)
返回Unix时间标记的一个字符串,根据format格式化。如果format为空默认会使用%Y-%m-%d %H:%i:%s的格式。


相关推荐
-
PHP8种变量类型的详细讲解2025-02-22 00:32:24
-
php+apache 和 php+nginx的区别2025-02-22 00:21:27
-
PHP:与workerman结合实现定时任务2025-02-22 00:15:57
-
Nginx的Rewrite规则与实例2025-02-22 00:15:39
-
MySql中身份证字段的简单脱敏介绍2025-02-22 00:15:36