最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何将这个出生日期转换为年龄在节点JS与猫鼬

运维笔记admin16浏览0评论

如何将这个出生日期转换为年龄在节点JS与猫鼬

如何将这个出生日期转换为年龄在节点JS与猫鼬

我使用节点JS表达对猫鼬。在前端有BDAY bmonth和登记byear字段。不过,我想将这些数据转换成年龄和单独保存在用户模式年龄后端。

功能

module.exports = {
  async CreateUser(req, res) {
    const schema = Joi.object().keys({
      username: Joi.string()
        .required(),
      email: Joi.string()
        .email()
        .required(),
      password: Joi.string()
        .required(),
        bday: Joi.number().integer()
        .required().min(2).max(2),
        bmonth: Joi.number().integer()
        .required().min(2).max(2),
        byear: Joi.number().integer()
        .required() 
    });

    const { error, value } = Joi.validate(req.body, schema);
    if (error && error.details) {
      return res.status(HttpStatus.BAD_REQUEST).json({ msg: error.details })
    }

    const userEmail = await User.findOne({
      email: Helpers.lowerCase(req.body.email)
    });
    if (userEmail) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: 'Email already exist' });
    }

    const userName = await User.findOne({
      username: Helpers.firstUpper(req.body.username)
    });
    if (userName) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: 'Username already exist' });
    }

    return bcrypt.hash(value.password, 10, (err, hash) => {
      if (err) {
        return res
          .status(HttpStatus.BAD_REQUEST)
          .json({ message: 'Error hashing password' });
      }
      const body = {
        username: Helpers.firstUpper(value.username),
        email: Helpers.lowerCase(value.email),
        bday: (value.bday),
         bmonth: (value.month),
       byear: (value.month),
        password: hash
      };
      User.create(body)
        .then(user => {
          const token = jwt.sign({ data: user }, dbConfig.secret, {
            expiresIn: '5h'
          });
          res.cookie('auth', token);
          res
            .status(HttpStatus.CREATED)
            .json({ message: 'User created successfully', user, token });
        })
        .catch(err => {
          res
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .json({ message: 'Error occured' });
        });
    });
  },

模型

username: { type: String },
  email: { type: String },
  password: { type: String },
   bday: { type: String },
  bmonth: { type: String },
  byear: { type: String },
  age: { type: String },

我认为有可以使用的功能模型即时,从诞生之日起计算年龄或内部将其转换上述功能,但不知道如何实现该结果的方法吗?如何从这些细节3岁获得(BDAY,bmonth,byear)?

回答如下:

您可以创建一个提供数据的新Date对象和计算年龄:

/**
 * Date from day / month / year
 *
 * @param day    The day of the date
 * @param month  The month of the date
 * @param year   The year of the date
 */
function dateFromDayMonthYear( day, month, year ) {
    return new Date( year, month - 1, day, 0, 0, 0, 0 );
}

/**
 * Get the years from now
 *
 * @param date  The date to get the years from now
 */
function yearsFromNow( date ) {
    return (new Date() - date) / 1000 / 60 / 60 / 24 / 365;
}

/**
 * Gets the age of a person
 *
 * @param birthDate  The date when the person was born
 */
function age( birthDate ) {
    return Math.floor( yearsFromNow( birthDate ) );
}

console.log( age( dateFromDayMonthYear( 7, 12, 2008 ) ) ); // 10
console.log( age( dateFromDayMonthYear( 17, 12, 2008 ) ) ); // 9

请记住,你可能想要做的dateFromDayMonthYear( parseInt( day ), parseInt( month ), parseInt( year ) ),因为你的初始值的字符串。

发布评论

评论列表(0)

  1. 暂无评论