【问题标题】:Getting exact format with momentjs and lodash使用 momentjs 和 lodash 获取准确的格式
【发布时间】:2021-05-06 23:27:30
【问题描述】:

我在这里有一个时间段列表,例如:

const times = [
      { start: '2020-07-09T08:00:00.000+02:00', end: '2020-07-09T09:30:00.000+02:00' },
      { start: '2020-07-09T08:30:00.000+02:00', end: '2020-07-09T10:00:00.000+02:00' },
    ]

当我尝试使用 momentjs 和 lodash 每天对它们进行 排序 以获得类似的东西时:

{
        {startTime: '08:00', endTime: '08:30'}
        {startTime: '08:30', endTime: '09:00'}
        {startTime: '08:00', endTime: '08:30'}
        {startTime: '08:30', endTime: '09:00'}
    }

我现在最终得到了这个解决方案:

const groupedAndFormatted = groupBy(times, date => moment(date.start_time).startOf('day').format('MMM Do YY')) 

但是这个并没有真正给我正确的解决方案,有什么想法吗?

【问题讨论】:

    标签: javascript momentjs lodash


    【解决方案1】:

    首先您需要将它们按正确的顺序排序,我们将使用排序和 unix 时间戳来完成此操作。

    然后将它们与 dddd 分组

    const times = [
      { start_time: '2020-07-09T08:00:00.000+02:00', endTime: '2020-07-09T09:30:00.000+02:00' },
      { start_time: '2020-07-09T08:30:00.000+02:00', endTime: '2020-07-09T10:00:00.000+02:00' },
      { start_time: '2020-07-07T09:00:00.000+02:00', endTime: '2020-07-07T10:30:00.000+02:00' }
    ];
    
    const sorted_times = times.sort((a,b) => moment(a.start_time).unix() - moment(b.start_time).unix())
    const grouped = _.groupBy(sorted_times, date => moment(date.start_time).format("dddd"))
    
    const formatted = _.mapValues(grouped, dates => {
      return dates.map(times => {
        return {
          start_time: moment(times.start_time).format("hh:mma"),
          endTime: moment(times.endTime).format("hh:mma"),
        }
      })
    })
    
    

    但是,如果您最终在不同日期有多个星期二,这将不起作用。

    【讨论】:

    • 感谢 Michael 的解决方案,但它没有给我这种格式的日期: startTime: '08:00' 但它给了我 iso 日期: startTime: '2020-07-09T08 :00:00.000+02:00'
    • @Errand,已更新。另请注意,奇怪的是你有蛇盒,然后是骆驼盒。对于start_timeendTime
    猜你喜欢
    • 2018-09-25
    • 2015-08-20
    • 2019-11-15
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多