如何在javascript中将日期转换为日期?

时间:2021-07-25 06:33:18

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对象转换为实际日期。例如:1929年第257天,我该怎么办呢?

8 个解决方案

#1


40  

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

“我想在一年中的某一天使用Date对象转换为实际日期。”

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.

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

For example:

例如:

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.

您还可以添加一些验证,以确保日期编号与所提供的年份的天数范围相符。

#2


5  

// You might need both parts of it-

//你可能需要它的两个部分 -

Date.fromDayofYear= function(n, y){
    if(!y) y= new Date().getFullYear();
    var d= new Date(y, 0, 1);
    return new Date(d.setMonth(0, n));
}
Date.prototype.dayofYear= function(){
    var d= new Date(this.getFullYear(), 0, 0);
    return Math.floor((this-d)/8.64e+7);
}

var d=new Date().dayofYear();
//
alert('day#'+d+' is '+Date.fromDayofYear(d).toLocaleDateString())


/*  returned value: (String)
day#301 is Thursday, October 28, 2010
*/

#3


5  

Here is a function that takes a day number, and returns the date object

optionally, it takes a year in YYYY format for parameter 2. If you leave it off, it will default to current year.

var getDateFromDayNum = function(dayNum, year){

    var date = new Date();
    if(year){
        date.setFullYear(year);
    }
    date.setMonth(0);
    date.setDate(0);
    var timeOfFirst = date.getTime(); // this is the time in milliseconds of 1/1/YYYY
    var dayMilli = 1000 * 60 * 60 * 24;
    var dayNumMilli = dayNum * dayMilli;
    date.setTime(timeOfFirst + dayNumMilli);
    return date;
}

OUTPUT

// OUTPUT OF DAY 232 of year 1995

var pastDate = getDateFromDayNum(232,1995)
console.log("PAST DATE: " , pastDate);

PAST DATE: Sun Aug 20 1995 09:47:18 GMT-0400 (EDT)

过去日期:1995年8月20日星期日09:47:18 GMT-0400(美国东部时间)

#4


2  

The shortest possible way is to create a new date object with the given year, January as month and your day of the year as date:

最短的方法是创建一个具有给定年份的新日期对象,1月作为月份,将您的年份作为日期创建:

const date = new Date(2017, 0, 365);

console.log(date.toLocaleDateString());

As for setDate the correct month gets calculated if the given date is larger than the month's length.

对于setDate,如果给定日期大于月份长度,则计算正确的月份。

#5


1  

You have a few options;

你有几个选择;

If you're using a standard format, you can do something like:

如果您使用的是标准格式,则可以执行以下操作:

new Date(dateStr);

If you'd rather be safe about it, you could do:

如果你更安全的话,你可以这样做:

var date, timestamp;
try {
    timestamp = Date.parse(dateStr);
} catch(e) {}
if(timestamp)
    date = new Date(timestamp);

or simply,    

new Date(Date.parse(dateStr));

Or, if you have an arbitrary format, split the string/parse it into units, and do:

或者,如果您有任意格式,请将字符串拆分/解析为单位,然后执行以下操作:

new Date(year, month - 1, day)

Example of the last:

最后一个例子:

var dateStr = '28/10/2010'; // uncommon US short date
var dateArr = dateStr.split('/');
var dateObj = new Date(dateArr[2], parseInt(dateArr[1]) - 1, dateArr[0]);

#6


1  

Here's my implementation, which supports fractional days. The concept is simple: get the unix timestamp of midnight on the first day of the year, then multiply the desired day by the number of milliseconds in a day.

这是我的实现,它支持小数天。概念很简单:在一年的第一天获取午夜的unix时间戳,然后将所需的日期乘以一天中的毫秒数。

/**
 * Converts day of the year to a unix timestamp
 * @param {Number} dayOfYear 1-365, with support for floats
 * @param {Number} year (optional) 2 or 4 digit year representation. Defaults to
 * current year.
 * @return {Number} Unix timestamp (ms precision)
 */
function dayOfYearToTimestamp(dayOfYear, year) {
  year = year || (new Date()).getFullYear();
  var dayMS = 1000 * 60 * 60 * 24;

  // Note the Z, forcing this to UTC time.  Without this it would be a local time, which would have to be further adjusted to account for timezone.
  var yearStart = new Date('1/1/' + year + ' 0:0:0 Z');

  return yearStart + ((dayOfYear - 1) * dayMS);
}

// usage

// 2015-01-01T00:00:00.000Z
console.log(new Date(dayOfYearToTimestamp(1, 2015)));

// support for fractional day (for satellite TLE propagation, etc)
// 2015-06-29T12:19:03.437Z
console.log(new Date(dayOfYearToTimestamp(180.51323423, 2015)).toISOString);

#7


0  

If I understand your question correctly, you can do that from the Date constructor like this

如果我正确理解你的问题,你可以从Date构造函数中这样做

new Date(year, month, day, hours, minutes, seconds, milliseconds)

All arguments as integers

所有参数都是整数

#8


0  

this also works ..

这也有效..

function to2(x) { return ("0"+x).slice(-2); }
function formatDate(d){
    return d.getFullYear()+"-"+to2(d.getMonth()+1)+"-"+to2(d.getDate());
    }
document.write(formatDate(new Date(2016,0,257)));

prints "2016-09-13"

打印“2016-09-13”

which is correct as 2016 is a leaap year. (see calendars here: http://disc.sci.gsfc.nasa.gov/julian_calendar.html )

这是正确的,因为2016年是一个闰年。 (见这里的日历:http://disc.sci.gsfc.nasa.gov/julian_calendar.html)

#1


40  

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

“我想在一年中的某一天使用Date对象转换为实际日期。”

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.

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

For example:

例如:

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.

您还可以添加一些验证,以确保日期编号与所提供的年份的天数范围相符。

#2


5  

// You might need both parts of it-

//你可能需要它的两个部分 -

Date.fromDayofYear= function(n, y){
    if(!y) y= new Date().getFullYear();
    var d= new Date(y, 0, 1);
    return new Date(d.setMonth(0, n));
}
Date.prototype.dayofYear= function(){
    var d= new Date(this.getFullYear(), 0, 0);
    return Math.floor((this-d)/8.64e+7);
}

var d=new Date().dayofYear();
//
alert('day#'+d+' is '+Date.fromDayofYear(d).toLocaleDateString())


/*  returned value: (String)
day#301 is Thursday, October 28, 2010
*/

#3


5  

Here is a function that takes a day number, and returns the date object

optionally, it takes a year in YYYY format for parameter 2. If you leave it off, it will default to current year.

var getDateFromDayNum = function(dayNum, year){

    var date = new Date();
    if(year){
        date.setFullYear(year);
    }
    date.setMonth(0);
    date.setDate(0);
    var timeOfFirst = date.getTime(); // this is the time in milliseconds of 1/1/YYYY
    var dayMilli = 1000 * 60 * 60 * 24;
    var dayNumMilli = dayNum * dayMilli;
    date.setTime(timeOfFirst + dayNumMilli);
    return date;
}

OUTPUT

// OUTPUT OF DAY 232 of year 1995

var pastDate = getDateFromDayNum(232,1995)
console.log("PAST DATE: " , pastDate);

PAST DATE: Sun Aug 20 1995 09:47:18 GMT-0400 (EDT)

过去日期:1995年8月20日星期日09:47:18 GMT-0400(美国东部时间)

#4


2  

The shortest possible way is to create a new date object with the given year, January as month and your day of the year as date:

最短的方法是创建一个具有给定年份的新日期对象,1月作为月份,将您的年份作为日期创建:

const date = new Date(2017, 0, 365);

console.log(date.toLocaleDateString());

As for setDate the correct month gets calculated if the given date is larger than the month's length.

对于setDate,如果给定日期大于月份长度,则计算正确的月份。

#5


1  

You have a few options;

你有几个选择;

If you're using a standard format, you can do something like:

如果您使用的是标准格式,则可以执行以下操作:

new Date(dateStr);

If you'd rather be safe about it, you could do:

如果你更安全的话,你可以这样做:

var date, timestamp;
try {
    timestamp = Date.parse(dateStr);
} catch(e) {}
if(timestamp)
    date = new Date(timestamp);

or simply,    

new Date(Date.parse(dateStr));

Or, if you have an arbitrary format, split the string/parse it into units, and do:

或者,如果您有任意格式,请将字符串拆分/解析为单位,然后执行以下操作:

new Date(year, month - 1, day)

Example of the last:

最后一个例子:

var dateStr = '28/10/2010'; // uncommon US short date
var dateArr = dateStr.split('/');
var dateObj = new Date(dateArr[2], parseInt(dateArr[1]) - 1, dateArr[0]);

#6


1  

Here's my implementation, which supports fractional days. The concept is simple: get the unix timestamp of midnight on the first day of the year, then multiply the desired day by the number of milliseconds in a day.

这是我的实现,它支持小数天。概念很简单:在一年的第一天获取午夜的unix时间戳,然后将所需的日期乘以一天中的毫秒数。

/**
 * Converts day of the year to a unix timestamp
 * @param {Number} dayOfYear 1-365, with support for floats
 * @param {Number} year (optional) 2 or 4 digit year representation. Defaults to
 * current year.
 * @return {Number} Unix timestamp (ms precision)
 */
function dayOfYearToTimestamp(dayOfYear, year) {
  year = year || (new Date()).getFullYear();
  var dayMS = 1000 * 60 * 60 * 24;

  // Note the Z, forcing this to UTC time.  Without this it would be a local time, which would have to be further adjusted to account for timezone.
  var yearStart = new Date('1/1/' + year + ' 0:0:0 Z');

  return yearStart + ((dayOfYear - 1) * dayMS);
}

// usage

// 2015-01-01T00:00:00.000Z
console.log(new Date(dayOfYearToTimestamp(1, 2015)));

// support for fractional day (for satellite TLE propagation, etc)
// 2015-06-29T12:19:03.437Z
console.log(new Date(dayOfYearToTimestamp(180.51323423, 2015)).toISOString);

#7


0  

If I understand your question correctly, you can do that from the Date constructor like this

如果我正确理解你的问题,你可以从Date构造函数中这样做

new Date(year, month, day, hours, minutes, seconds, milliseconds)

All arguments as integers

所有参数都是整数

#8


0  

this also works ..

这也有效..

function to2(x) { return ("0"+x).slice(-2); }
function formatDate(d){
    return d.getFullYear()+"-"+to2(d.getMonth()+1)+"-"+to2(d.getDate());
    }
document.write(formatDate(new Date(2016,0,257)));

prints "2016-09-13"

打印“2016-09-13”

which is correct as 2016 is a leaap year. (see calendars here: http://disc.sci.gsfc.nasa.gov/julian_calendar.html )

这是正确的,因为2016年是一个闰年。 (见这里的日历:http://disc.sci.gsfc.nasa.gov/julian_calendar.html)