Fork me on GitHub

Java 实现 Timstamp 和 String 互相转换

Java 实现 Timstamp 和 String 互相转换


 

1、代码实现

package com.miracle.luna.timestamp;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;

/**
 * Created by Miracle Luna on 2020/8/28
 */
public class TestTimestamp {
    public static void main(String[] args) {
        // 获取当前系统时间的时间戳
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        // 将 Timestamp 类型转为 String 类型
        String currentTimeStr = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(currentTime);
        System.out.println("==> currentTimeStr: " + currentTimeStr);

        // 将 String 类型转为 Timestamp 类型
        String timeStr = "2020-08-28 01:56:20";
        Timestamp timestamp = Timestamp.valueOf(timeStr);
        System.out.println("\n--> timestamp: " + timestamp);

        // 如果时间格式想显示为:2020-08-28T12:23:34Z
        String currentTimeStr_TZ = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss'Z'").format(currentTime);
        System.out.println("\n==> currentTimeStr_TZ: " + currentTimeStr_TZ);
    }
}

 

2、运行结果

==> currentTimeStr: 2020-08-28 02:04:01

--> timestamp: 2020-08-28 01:56:20.0

==> currentTimeStr_TZ: 2020-08-28T02:04:01Z

 

 

posted @ 2020-08-28 02:05  龙凌云端  阅读(616)  评论(0编辑  收藏  举报