Get the local date instead of UTC

纵饮孤独 提交于 2020-06-09 05:26:07

问题


The following script calculates me next Friday and next Sunday date.

The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring. What should I do ?

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

回答1:


If you worry that the date is wrong in some timezones, try normalising the time

To NOT use toISO you can do this

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)



回答2:


You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?

The nextFriday is a date object. Would it work if you use the get-functions instead? e.g.

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


来源:https://stackoverflow.com/questions/62259606/get-the-local-date-instead-of-utc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!