javascript - 距离下一个生日的剩余时间javascript
问题描述
我正在尝试构建一个应用程序,用户可以从日历中选择他们的生日,该应用程序会以天、小时、分钟和秒的形式向用户显示他们的年龄和到下一个生日的剩余时间。我正在使用反应日历和时刻。不知何故,我得到了用户年龄,但我不知道如何获得剩余时间。这是我的代码:
import React, { Component } from "react";
import Calendar from "react-calendar";
import moment from "moment";
export default class App extends Component {
state = {
date: new Date(),
age: null,
timeRemaining: {
days: 0,
hours: 0,
minutes: 0,
seconds: 0
}
};
onChange = date => this.setState({ date });
handleClick = () => {
const birthday = moment(this.state.date).toDate();
const now = new Date();
const currentYear = now.getFullYear();
const birthYear = birthday.getFullYear();
let age = currentYear - birthYear;
if (now < new Date(birthday.setFullYear(currentYear))) {
age = age - 1;
}
this.setState({ age });
};
render() {
console.log(this.state.date);
console.log(this.state.age);
return (
<div>
<Calendar
onChange={this.onChange}
value={this.state.date}
onClickDay={this.handleClick}
/>
<div>{this.state.age}</div>
</div>
);
}
}
解决方案
我不知道这是否是您要查找的内容,但是通过此代码,我可以知道距离下一个生日还有多少个月和几天
const birthday = new Date(1992, 5, 22);
const currentDate = new Date(Date.now());
const birthdayMonth = birthday.getMonth();
const birthdayDay = birthday.getDate();
const nextBirthday = new Date(currentDate.getFullYear(), birthdayMonth, birthdayDay).getTime() < currentDate.getTime()
? new Date(currentDate.getFullYear() + 1, birthdayMonth, birthdayDay)
: new Date(currentDate.getFullYear(), birthdayMonth, birthdayDay);
let remainingTime = nextBirthday.getTime() - currentDate.getTime();
const remainingMonths = Math.floor((remainingTime / 1000) / (60 * 60 * 24 * 30));
remainingTime -= remainingMonths * (60 * 60 * 24 * 30 * 1000);
const remainingDays = Math.floor((remainingTime / 1000) / (60 * 60 * 24));
console.log(`Remaining ${remainingMonths} months and ${remainingDays} days until your birthday`);
推荐阅读
- typescript - Typescript:是否可以表明 Promise 使用特定类型解析和拒绝?
- apache-spark - 如何通过 Spark 2.3 (pyspark) 在 Hive 3.1 中创建镶木地板表
- gif - 如何使用 gif_lib 将 RGB 编码为 gif
- laravel-5 - Laravel Homestead 无法连接到服务器 127.0.0.1
- ubuntu - Gitlab导出:找不到捆绑和耙
- python - 用transformation.py的superimposition_matrix计算变换矩阵的问题
- python-3.x - 查找 3-D numpy 数组索引的最快方法
- python - 用子函数的“return”中断包含“while True”的主函数
- python - 从 python 图像下载检查字节时,Bytes.startswith 给出了两个不同的答案
- android - 如何从 android 中的 DialogFlow 代理获取文本响应?