为了账号安全,请及时绑定邮箱和手机立即绑定

获取本地日期而不是 UTC

获取本地日期而不是 UTC

DIEA 2022-09-23 16:37:25

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


问题 :使用 .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('-');


查看完整描述

2 回答

?
慕丝7291255

TA贡献1504条经验 获得超6个赞

如果您担心某些时区的日期有误,请尝试对时间进行规范化


要不使用 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)


查看完整回答
反对 回复 5天前
?
温温酱

TA贡献1439条经验 获得超2个赞

你担心 [年耶,嗯,日]是世界协调时而不是当前的时间区吗?


下一个星期五是一个日期对象。如果您改用 get 函数,它会起作用吗?例如


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


查看完整回答
反对 回复 5天前
  • 2 回答
  • 0 关注
  • 9 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信