JS格式化時間(支援小程式,相容IOS)

來源:互聯網
上載者:User

標籤:pre   iso   color   const   let   ons   safari   格式   tostring   

const REGEX = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/
export const formatTime = (val, format)=>{
if (val) {
/**
* @instructions 如果不是時間戳記格式,且含有字元 ‘-‘ 則將 ‘-‘ 替換成 ‘/‘ && 刪除小數點及後面的數字
* @reason 將 ‘-‘ 替換成 ‘/‘ && 刪除小數點及後面的數字 的原因是safari瀏覽器僅支援 ‘/‘ 隔開的時間格式
*/
if (val.toString().indexOf(‘-‘) > 0) {
val = val.replace(/T/g, ‘ ‘).replace(/\.[\d]{3}Z/, ‘‘).replace(/(-)/g, ‘/‘); // 將 ‘-‘ 替換成 ‘/‘
val = val.slice(0, val.indexOf(".")); // 刪除小數點及後面的數字
}
let date = new Date(val);
date.setHours(date.getHours() + 8);
const [whole, yy, MM, dd, hh, mm, ss] = date.toISOString().match(REGEX);
const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const dates = new Date().getDate();
if (format) {
return format
.replace(‘yyyy‘, yy)
.replace(‘yy‘, yy.slice(2))
.replace(‘MM‘, MM)
.replace(‘dd‘, dd)
.replace(‘hh‘, hh)
.replace(‘mm‘, mm)
.replace(‘ss‘, ss)
} else {
return [yy, MM, dd].join(‘-‘) + ‘ ‘ + [hh, mm, ss].join(‘:‘);
}
} else {
return ‘--‘;
}
}

JS格式化時間(支援小程式,相容IOS)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.