开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 9 天,点击查看活动详情
手把手教你分析身份证的身份证号码
❤ 识别身份证并且生成生日
① 拿到数字
身份证的有效 长度为 18 位数
所以先进入判断 length === 18
位
if(idCard.length === 18){}
定义一个假的身份证:
var idCard="141034199805060011";
从第6开始截取8 位,即它的出生年月日
var birthday = idCard.substr(6, 8);
输出结果 19980506
,再用正则替换一下拿到我们想要的格式
birthday = birthday.replace(/(.{4})(.{2})/, '2-');
console.log(birthday);
//最后输出结果 输出 1998-05-06
② 规范格式
拿到结果以后对结果进行格式规范
支持两个参数 : 传入的参数 : 以及格式类型 dateFormat(birthday, 'yyyy-MM-dd');
dateFormat(odate, formatStr) {
let format = formatStr || 'yyyy-MM-dd hh:mm:ss'
const date = new Date(odate)
if (date !== 'Invalid Date') {
const o = {
'M+': date.getMonth() + 1, // month
'd+': date.getDate(), // day
'h+': date.getHours(), // hour
'm+': date.getMinutes(), // minute
's+': date.getSeconds(), // second
'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
'S': date.getMilliseconds() // millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1,
(date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (const k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1,
RegExp.$1.length === 1 ? o[k]
: ('00' + o[k]).substr(('' + o[k]).length))
}
}
return format
}
return ''
},
其中:中国标准时间转化可以利用转化时间
time(date) {
var y = date.getFullYear()
var m = date.getMonth() + 1
m = m < 10 ? '0' + m : m
var d = date.getDate()
d = d < 10 ? '0' + d : d
var h = date.getHours()
h = h < 10 ? '0' + h : h
var minute = date.getMinutes()
minute = minute < 10 ? '0' + minute : minute
var second = date.getSeconds()
second = second < 10 ? '0' + second : second
return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
},
时间格式转化:
//时间格式转换
var date = new Date("2020-05-12T09:18:51.000+0000");
var date1 = this.time(date);
console.log(date1)
时间上另外一种处理方式就是引入 dayjs (一个轻量的处理时间和日期的javascript库)
下载 npm install dayjs --save
main.js 中 全局引入
import dayjs from ‘dayjs’ Vue.prototype.dayjs = dayjs;