将时间戳转化为日期格式

Python010

将时间戳转化为日期格式,第1张

1. 将时间转换成日期格式

function timestampToTime(timestamp) {

        var date = new Date(timestamp * 1000)//时间戳为10位需*1000,时间戳为13位的话不需乘1000

        Y = date.getFullYear() + '-'

        M = (date.getMonth()+1 <10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'

        D = date.getDate() + ' '

        h = date.getHours() + ':'

        m = date.getMinutes() + ':'

        s = date.getSeconds()

        return Y+M+D+h+m+s

    }

    timestampToTime(1403058804)

    console.log(timestampToTime(1403058804))//2014-06-18 10:33:24

注意:如果是Unix时间戳记得乘以1000。比如:

2. 将日期格式转换成时间戳:

var date = new Date('2014-04-23 18:55:49:123')

    // 有三种方式获取

    var time1 = date.getTime()

    var time2 = date.valueOf()

    var time3 = Date.parse(date)

    console.log(time1)//1398250549123

    console.log(time2)//1398250549123

    console.log(time3)//1398250549000

时间戳就是如1377216000000 这种格式我们在mysql数据库中会经常用到把时间转换成时间戳或把时间戳转换成日期格式了,下面我来介绍安卓中时间戳操作转换方法。

一、原理

时间戳的原理是把时间格式转为十进制格式,这样就方便时间的计算。好~ 直接进入主题。(下面封装了一个类,有需要的同学可以参考或是直接Copy 就可以用了。)

如: 2013年08月23日 转化后是 1377216000000

二、步骤

1、创建 DateUtilsl类。

代码如下 复制代码

importjava.text.ParseException

importjava.text.SimpleDateFormat

importjava.util.Date

/*

* @author Msquirrel

*/

public class DateUtils {

privateSimpleDateFormat sf = null

/*获取系统时间 格式为:"yyyy/MM/dd "*/

public static String getCurrentDate() {

Date d = newDate()

sf = newSimpleDateFormat("yyyy年MM月dd日")

returnsf.format(d)

}

/*时间戳转换成字符窜*/

public static String getDateToString(long time) {

Date d = newDate(time)

sf = newSimpleDateFormat("yyyy年MM月dd日")

returnsf.format(d)

}

/*将字符串转为时间戳*/

public static long getStringToDate(String time) {

sdf = newSimpleDateFormat("yyyy年MM月dd日")

Date date = newDate()

try{

date = sdf.parse(time)

} catch(ParseException e) {

// TODO Auto-generated catch block

e.printStackTrace()

}

returndate.getTime()

}

2、在对应使用的地方调用就可以了。

代码如下 复制代码

DateUtils.getCurrentDate()//获取系统当前时间

DateUtils.getDateToString(时间戳)//时间戳转为时间格式

DateUtils.getStringToDate("时间格式")//时间格式转为时间戳

// 时间戳转换成日期格式

export const getTimeData = function(time){

let date = new Date(time)

let Y = date.getFullYear()

let M = date.getMonth()+1 <10 ? '0'+(date.getMonth()+1) : date.getMonth()+1

let D = date.getDate() <10 ? '0'+date.getDate() : date.getDate()

let h = date.getHours() <10 ? '0'+date.getHours() : date.getHours()

let m = date.getMinutes() <10 ? '0'+date.getMinutes() : date.getMinutes()

let s = date.getSeconds() <10 ? '0'+date.getSeconds() : date.getSeconds()

return Y+'-'+M+'-'+D+' '+h+':'+m+':'+s//转换为年月日时分秒

}