首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >下一个生日的剩余时间javascript

下一个生日的剩余时间javascript
EN

Stack Overflow用户
提问于 2020-02-12 23:37:54
回答 2查看 90关注 0票数 1

我正在尝试建立一个应用程序,用户可以选择他们的生日从日历和应用程序显示他们的年龄和剩余的时间,直到他们的下一个生日以天,小时,分钟和秒。我使用的是react-calendar和moment。不知何故,我得到了用户年龄,但我不知道如何获得剩余时间。下面是我的代码:

代码语言: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>
    );
  }
}
EN

回答 2

Stack Overflow用户

发布于 2020-02-12 23:57:55

我不知道这是否是你想要的,但是有了这段代码,我可以知道离下一个生日还有多少个月和多少天

代码语言:javascript
复制
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`);
票数 1
EN

Stack Overflow用户

发布于 2020-02-13 00:09:27

由于您已经在使用moment.js,因此可以使用moment.js的比较方法。

代码语言:javascript
复制
// your specific birthday you want to compare
const myBirthday: Moment = moment("2020/01/03");
// date of today
const today: Moment = moment();
// if birthday is in past, add one year
if (today > myBirthday) {
  myBirthday.add(1, "year");
}
// calculate duration of difference between those two days
const duration: Duration = moment.duration(myBirthday.diff(today));
// output the duration as you wish
console.log(duration.get("month"));
console.log(duration.get("days"));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60191907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档