Java将Unix时间戳转换成指定格式日期

来源:互联网 发布:少儿编程 比尔盖茨 编辑:程序博客网 时间:2024/05/20 21:48

Java将Unix时间戳转换成指定格式日期

当从服务器获取数据的时候,有时候获取的数据中的时间在很多的情况下是时间戳类似于这样1473048265,当然,我们不可能将这些数据以时间戳的形式展示给用户,通常情况,是要对这个时间戳进行一系列的处理加工,使其变成我们想要并习惯浏览的那种格式,那么怎么处理这些时间戳格式的数据呢?每个语言和框架都有自己的方法和方式。

下面将以Java的方法来实现,废话少说直接撸码……

方法实现

    /**     * Java将Unix时间戳转换成指定格式日期字符串     * @param timestampString 时间戳 如:"1473048265";     * @param formats 要格式化的格式 默认:"yyyy-MM-dd HH:mm:ss";     *     * @return 返回结果 如:"2016-09-05 16:06:42";     */    public static String TimeStamp2Date(String timestampString, String formats) {        if (TextUtils.isEmpty(formats))            formats = "yyyy-MM-dd HH:mm:ss";        Long timestamp = Long.parseLong(timestampString) * 1000;        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));        return date;    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

调用方法

TimeStamp2Date("1473048265", "yyyy-MM-dd HH:mm:ss");
  • 1
  • 1

返回结果

2016-09-05 16:06:42

将Java指定格式日期转换成Unix时间戳

    /**     * 日期格式字符串转换成时间戳     *     * @param dateStr 字符串日期     * @param format   如:yyyy-MM-dd HH:mm:ss     *     * @return     */    public static String Date2TimeStamp(String dateStr, String format) {        try {            SimpleDateFormat sdf = new SimpleDateFormat(format);            return String.valueOf(sdf.parse(dateStr).getTime() / 1000);        } catch (Exception e) {            e.printStackTrace();        }        return "";    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

取得当前时间戳(精确到秒)

    /**     * 取得当前时间戳(精确到秒)     *     * @return nowTimeStamp     */    public static String getNowTimeStamp() {        long time = System.currentTimeMillis();        String nowTimeStamp = String.valueOf(time / 1000);        return nowTimeStamp;    }
0 0
原创粉丝点击