英文:
convert dates using moment js
问题
我有一个日期对象
const resDate={startDate: "Fri Apr 21 2023 00:00:00 GMT+0530 (India Standard Time)", endDate: "Tue Apr 25 2023 00:00:00 GMT+0530 (India Standard Time)"}
我的目标是将 startDate 和 endDate 转换为以下格式的 const
const resDate={startDate: "2022-09-01T00:00:00+05:30", endDate: "2022-09-01T00:00:00+05:30"}
在这个示例中,值不重要,重要的是转换的格式。我使用了 Moment.js 来执行这个任务,并创建了一个函数来实现这一目标。
const getDate = () => {
let effTime = moment(startDate).format('YYYY-MM-DD');
let istTime = effTime + "T00:00:00+05:30";
return istTime;
}
但是这似乎不是正确的方法,因为我在函数中硬编码了一些内容。是否有正确的方法来做这个?
英文:
I am having a date object
const resDate={startDate: "Fri Apr 21 2023 00:00:00 GMT+0530 (India Standard Time)", endDate: "Tue Apr 25 2023 00:00:00 GMT+0530 (India Standard Time)"}
my aim is to get startDate and endDate in a format like const
const resDate={startDate:2022-09-01T00:00:00+05:30,endDate: 2022-09-01T00:00:00+05:30}
and so on values doesn't make sense in this example the format of conversion matters .I used moment js to carry out this task and created a function for this
const getDate=()=>{
let effTime = moment(startDate).format('YYYY-MM-DD');
let istTime= effTime + "T00:00:00+05:30";
return isTime;
}
but this doesn't seems to be the right approach as i am hardcoding something in the function .is there a correct way to do this?
答案1
得分: 0
首先,与momentjs的最新发展不鼓励。不过,您可以在没有momentjs的情况下执行此操作:
function formatDate(date) {
const [, mmm, d, y, h, m, s, _, zh, zm] = date.match(/[+-]\d\d|\w+/g);
const M = "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(mmm) / 3;
return new Date(Date.UTC(y, M, d, h, m, s)).toJSON().slice(0, 19) + zh + ":" + zm;
}
// Example
const startDate = "Fri Apr 21 2023 00:00:00 GMT+0530 (India Standard Time)";
const result = formatDate(startDate);
console.log(result);
英文:
First of all, new developments with momentjs are discouraged. You could do this without momentjs though:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function formatDate(date) {
const [, mmm, d, y, h, m, s, _, zh, zm] = date.match(/[+-]\d\d|\w+/g);
const M = "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(mmm) / 3;
return new Date(Date.UTC(y, M, d, h, m, s)).toJSON().slice(0, 19) + zh+":"+zm;
}
// Example
const startDate = "Fri Apr 21 2023 00:00:00 GMT+0530 (India Standard Time)";
const result = formatDate(startDate);
console.log(result);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论