js 获取身份证号的出生日期
时间: 2023-12-02 15:04:07 浏览: 27
可以使用正则表达式来从身份证号码中提取出生日期。
以下是一个示例代码:
```javascript
function getBirthday(idCard) {
const birthday = idCard.substr(6, 8);
return birthday.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");
}
const idCard = "330102199001011234";
console.log(getBirthday(idCard)); // 输出:1990-01-01
```
代码中,`getBirthday` 函数接收一个身份证号码作为参数,然后从第7个字符开始,取出8个字符,即出生日期的年月日部分。接着使用正则表达式将年月日格式化为"xxxx-xx-xx"的形式,并返回结果。
注意:以上代码仅支持18位身份证号码,如果需要支持15位身份证号码,需要进行一些修改。
相关问题
微信小程序通过js识别输入框输入的身份证号获取获取出生日期、年龄、性别
可以使用 JavaScript 的正则表达式来识别身份证号并获取出生日期、年龄、性别。以下是一个简单的示例代码:
```javascript
// 获取输入框的身份证号
var idCard = document.getElementById('idCardInput').value;
// 正则表达式匹配身份证号
var reg = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$/;
var match = idCard.match(reg);
if (match) {
// 获取出生日期
var birthdate = match[2] + '-' + match[3] + '-' + match[4];
// 计算年龄
var age = new Date().getFullYear() - parseInt(match[2], 10);
// 获取性别
var gender = parseInt(match[5], 10) % 2 === 1 ? '男' : '女';
// 在控制台输出结果
console.log('出生日期:' + birthdate);
console.log('年龄:' + age);
console.log('性别:' + gender);
} else {
console.log('身份证号格式不正确');
}
```
以上代码假设身份证号输入框的 ID 为 `idCardInput`。在实际应用中,你需要根据具体的场景和要求进行相应的修改和适配。
微信小程序识别输入框输入的身份证号获取获取出生日期、年龄、性别
可以通过微信小程序的API实现身份证号的解析,获取出生日期、年龄、性别等信息。以下是一个简单的实现过程:
1. 在wxml文件中定义一个输入框:
```
<view class="input-wrapper">
<input type="number" placeholder="请输入身份证号" bindinput="onInputIdCard" />
</view>
```
2. 在js文件中实现onInputIdCard方法,获取输入的身份证号码:
```
onInputIdCard(e) {
const idCard = e.detail.value
// TODO: 对身份证号进行校验
}
```
3. 对输入的身份证号进行校验,确保其合法性。
4. 调用微信小程序提供的API wx.getStorageSync,获取身份证号中的出生日期、年龄、性别等信息:
```
const idCardInfo = getIdCardInfo(idCard)
console.log(idCardInfo)
function getIdCardInfo(idCard) {
const year = idCard.substring(6, 10)
const month = idCard.substring(10, 12)
const day = idCard.substring(12, 14)
const sex = idCard.substring(16, 17) % 2 === 0 ? '女' : '男'
const birthday = year + '-' + month + '-' + day
const age = getAge(year, month, day)
return { birthday, age, sex }
}
function getAge(year, month, day) {
const now = new Date()
const currentYear = now.getFullYear()
const currentMonth = now.getMonth() + 1
const currentDay = now.getDate()
let age = currentYear - year
if (currentMonth < month || (currentMonth === month && currentDay < day)) {
age--
}
return age
}
```
解析身份证号码的逻辑比较简单,主要是通过字符串截取的方式获取出生日期、性别等信息。年龄的计算需要根据当前时间和出生日期计算得出。