如何在javascript中将日期转换为日期? [英] how can I convert day of year to date in javascript?

查看:152
本文介绍了如何在javascript中将日期转换为日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一年中的某一天使用Date对象转换为实际日期。例如:1929年第257天,我怎么能这样做?

I want to take a day of the year and convert to an actual date using the Date object. Example: day 257 of 1929, how can I go about doing this?

推荐答案


我想要使用Date对象获取一年中的一天并转换为实际日期。

"I want to take a day of the year and convert to an actual date using the Date object."

重新阅读您的问题后,它听起来你有一个年份编号和一个任意的日期编号(例如 0..365 中的数字(或闰年为366)),你想得到该日期。

After re-reading your question, it sounds like you have a year number, and an arbitrary day number (e.g. a number within 0..365 (or 366 for a leap year)), and you want to get a date from that.

例如:

dateFromDay(2010, 301); // "Thu Oct 28 2010", today ;)
dateFromDay(2010, 365); // "Fri Dec 31 2010"

如果是这样,可以轻松完成:

If it's that, can be done easily:

function dateFromDay(year, day){
  var date = new Date(year, 0); // initialize a date in `year-01-01`
  return new Date(date.setDate(day)); // add the number of days
}

您还可以添加一些验证,以确保日期数字与所提供的一年中的天数有关。

You could add also some validation, to ensure that the day number is withing the range of days in the year supplied.

这篇关于如何在javascript中将日期转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆