Unix 时间戳是从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。
以下2个方法源自于时间工具包:time utils
效果展示:在线时间戳转换工具
时间转时间戳
- /**
- * 将某个时间转化成时间戳
- * 时间格式:2019-05-20 00:00:00 或 2019年5月1日 00:00:00
- * 返回值:1556640000000,13位时间戳
- */
- function Jh_convertTimeStamp(time: string): number {
- // 用正则主要是把“2019-05-20 00:00:00”转换成“2019/05/20 00:00:00”兼容ios
- let newTime = time.replace(/-|\./g, '/')
- // console.log(newTime);
- // newTime = newTime.replace(/\./g, "-");
- newTime = newTime.replace(/年/g, '/')
- newTime = newTime.replace(/月/g, '/')
- newTime = newTime.replace(/日/g, '')
- if (newTime.length === 4) {
- newTime = newTime + '/01/01 00:00:00'
- }
- if (newTime.length === 7) {
- newTime = newTime + '/01 00:00:00'
- }
- if (newTime.length === 10) {
- newTime = newTime + ' 00:00:00'
- }
- if (newTime.length === 16) {
- newTime = newTime + ':00'
- }
- return Date.parse(newTime)
- }
复制代码 使用示例- let res = Jh_convertTimeStamp('2024-05-31 14:16:39')
复制代码 时间戳转换时间
- /**
- * 将某个时间戳转化成 指定格式时间
- * @param {date} time 时间 new Date().getTime()
- * @param {string} cFormat {y}-{m}-{d} {h}:{i}:{s} {w}
- */
- function Jh_timeStampToTime(time: string | number | Date, cFormat: string): string {
- if (arguments.length === 0) {
- return ''
- }
- const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
- let date: Date
- if (typeof time === 'object') {
- date = time as Date
- } else {
- if (('' + time).length === 10) time = parseInt(time as string) * 1000
- date = new Date(time)
- }
- const formatObj: any = {
- y: date.getFullYear(),
- m: date.getMonth() + 1,
- d: date.getDate(),
- h: date.getHours(),
- i: date.getMinutes(),
- s: date.getSeconds(),
- w: date.getDay()
- }
- const time_str = format.replace(/{(y|m|d|h|i|s|w)+}/g, (result, key) => {
- let value = formatObj[key]
- if (key === 'w') {
- return ['日', '一', '二', '三', '四', '五', '六'][value]
- }
- if (result.length > 0 && value < 10) {
- value = '0' + value
- }
- return value || 0
- })
- return time_str
- }
复制代码 使用示例:- let res = Jh_timeStampToTime(1717136199178, '{y}-{m}-{d} {h}:{i}:{s}')
复制代码 Tools-Web是一个免费开源工具站;只需简单几步,即可快速搭建属于自己的综合工具站,支持docker一键部署。
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |