获取本地日期而不是 UTC

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


问题 :使用 .toISO 字符串使用 UTC 时间。我需要用输出本地时间的东西来改变。我对 javascript 非常陌生,所以我找不到合适的属性来代替 .to 等字符串。我该怎么办?


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('-');


DIEA
浏览 79回答 2
2回答

慕丝7291255

如果您担心某些时区的日期有误,请尝试对时间进行规范化要不使用 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)

温温酱

你担心 [年耶,嗯,日]是世界协调时而不是当前的时间区吗?下一个星期五是一个日期对象。如果您改用 get 函数,它会起作用吗?例如const nextFridayYear = nextFriday.getFullYear();// get month is zero index based, i have added oneconst nextFridayMonth = (nextFriday.getMonth() + 1).toString()    .padStart(2, '0');const nextFridayDay = today.getDate().toString()    .padStart(2, '0');
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript