使用Moment.js转换日期。

huangapple go评论58阅读模式
英文:

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 = &quot;JanFebMarAprMayJunJulAugSepOctNovDec&quot;.indexOf(mmm) / 3;
    return new Date(Date.UTC(y, M, d, h, m, s)).toJSON().slice(0, 19) + zh+&quot;:&quot;+zm;
}

// Example
const startDate = &quot;Fri Apr 21 2023 00:00:00 GMT+0530 (India Standard Time)&quot;;
const result = formatDate(startDate);
console.log(result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月11日 02:24:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定