0

以下脚本计算我下周五和下周日的日期。

问题:使用 .toISOString 使用 UTC 时间。我需要改变一些输出当地时间的东西。我对 javascript 很陌生,所以我找不到合适的属性来代替 .toIsostring。我该怎么办 ?

function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date || new Date());
  ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
  return ret;
}

let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);

console.log('Next Friday     : ' + nextFriday.toDateString() +
  '\nFollowing Sunday: ' + followingSunday.toDateString());

/* Previous code calculates next friday and next sunday dates */


var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');

4

2 回答 2

3

如果您担心某些时区的日期有误,请尝试将时间标准化

不使用 toISO 你可以这样做

const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', 
  { year: 'numeric', month: '2-digit', day: '2-digit' })
  .split("/")

function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date || new Date());
  ret.setHours(15, 0, 0, 0); // normalise
  ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
  return ret;
}

let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);

console.log('Next Friday     : ' + nextFriday.toDateString() +
  '\nFollowing Sunday: ' + followingSunday.toDateString());

/* Previous code calculates next friday and next sunday dates */


var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');

console.log(yyyy, mm, dd)

// not using UTC: 

const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")

console.log(yyyy1, mm1, dd1)

于 2020-06-08T10:11:48.120 回答
0

您担心 [yyyy,mm,dd] 是 UTC 而不是当前时区?

nextFriday 是一个日期对象。如果您使用 get-functions 代替它会起作用吗?例如

const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
    .padStart(2, '0');
const nextFridayDay = today.getDate().toString()
    .padStart(2, '0');
于 2020-06-08T10:18:42.070 回答