1. 程式人生 > >js 關於日期的格式化

js 關於日期的格式化

第一種:將時間戳轉化為標準時間

方法一:
var date = new Date(時間戳); //獲取一個時間物件
function format(fmt, date) {
				var o = {
					"M+": date.getMonth() + 1, //月份   
					"d+": date.getDate(), //日   
					"h+": date.getHours(), //小時   
					"m+": date.getMinutes(), //分   
					"s+": date.getSeconds(), //秒   
					"q+": Math.floor((date.getMonth() + 3) / 3), //季度   
					"S": date.getMilliseconds() //毫秒   
				};
				if (/(y+)/.test(fmt))
					fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
				for (var k in o)
					if (new RegExp("(" + k + ")").test(fmt))
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
  呼叫函式把var times= new Date(時間戳)獲取到的時間轉化為標準時間
  呼叫方式
	console.log(format('yyyy-MM-dd hh:mm:ss', times))
	console.log(format('yyyy-MM-dd', times))
	console.log(format('yyyy/MM/dd', times))
	console.log(format('yyyy年MM月dd日', times))
方法二:
//  日期的格式化 code = new Date() var data = (new Date()).getTime() 獲取時間戳 
 引數說明: code為時間戳, true表示顯示年月日  false表示顯示年月日很時間
export function formatTimes(code, boolean) {
  const time = new Date(code)
  const year = time.getFullYear()
  const month = time.getMonth() + 1
  const date = time.getDate()
  const hour = time.getHours() < 10 ? '0' + time.getHours() : time.getHours()
  const min = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
  const sec = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
  if (boolean) {
    return year + '-' + month + '-' + date + ''
  } else {
    return year + '-' + month + '-' + date + '.' + hour + ':' + min + ':' + sec
  }
}

第二種:將標準時間轉化為時間戳
var nowData = new Date();
有三種方式可以將標準時間轉化為時間戳
區別如下:
var time1 = nowData.getTime();
var time2 = nowData.valueOf();
var time3 = Date.parse(nowData);
前兩種是精確到毫秒,後面一種精確到秒
//1532868592176
//1532868592176
//1532868592000

這次在專案開發的時候後臺返給我的資料是精確到秒,但是沒有返回後面的三個零,前端處理的時候要加上三個零