如何从工作日和时间字符串创建 JS 日期对象
How to create a JS Date object from weekday and time string
给定一个像 Tue:18-20
这样的字符串,如何创建一个 Javascript 日期对象来表示 first/next 星期二 18:00(从现在开始)
对于上下文:以上字符串格式用于存储用户的取件和送货时间偏好。很想知道是否有更好的方法来存储它(作为字符串或不同的格式)
首先,编写代码来解码您的 <day>:<startHours>-<endHours>
字符串。然后,你可以这样做
let day = 1; // Mon : 1, Tue: 2, Wed: 3 ...
let startHours = 18;
let endHours= 20;
// get the start of the period
let dateStart = new Date();
dateStart.setDate(dateStart.getDate() + (day !== dateStart.getDay() ? (day + 7 - dateStart.getDay()) % 7 : 7));
dateStart.setHours(startHours, 0, 0, 0)
console.log(dateStart)
// get the end of the period
let dateEnd = new Date();
dateEnd.setDate(dateEnd.getDate() + (day !== dateEnd.getDay() ? (day + 7 - dateEnd.getDay()) % 7 : 7));
dateEnd.setHours(endHours, 0, 0, 0)
console.log(dateEnd)
给定一个像 Tue:18-20
这样的字符串,如何创建一个 Javascript 日期对象来表示 first/next 星期二 18:00(从现在开始)
对于上下文:以上字符串格式用于存储用户的取件和送货时间偏好。很想知道是否有更好的方法来存储它(作为字符串或不同的格式)
首先,编写代码来解码您的 <day>:<startHours>-<endHours>
字符串。然后,你可以这样做
let day = 1; // Mon : 1, Tue: 2, Wed: 3 ...
let startHours = 18;
let endHours= 20;
// get the start of the period
let dateStart = new Date();
dateStart.setDate(dateStart.getDate() + (day !== dateStart.getDay() ? (day + 7 - dateStart.getDay()) % 7 : 7));
dateStart.setHours(startHours, 0, 0, 0)
console.log(dateStart)
// get the end of the period
let dateEnd = new Date();
dateEnd.setDate(dateEnd.getDate() + (day !== dateEnd.getDay() ? (day + 7 - dateEnd.getDay()) % 7 : 7));
dateEnd.setHours(endHours, 0, 0, 0)
console.log(dateEnd)