有没有办法对格式化为 AM/PM 的字符串的时间进行排序?

Is there a way to sort times that are formatted into strings of AM/PM?

我想按拾取时间对一组对象进行排序,但我需要将时间格式化为排序后它们在下面的数组中的格式。显然,我 运行 遇到的问题是您不能像使用整数那样使用 .sort() 对字符串进行排序。

有没有办法使用 .sort() 将这些从最早时间排序到最晚时间?或者,如果没有,是否有办法将它们格式化为整数,然后重新格式化并将它们推回到对象中各自的位置?

[{pickupTime='10:30 AM', pickupTime='4:00 AM', pickupTime='6:30 AM',pickupTime='12:00 PM',pickupTime='1:00 PM'}, [{pickupTime='9:00 AM',pickupTime='6:00 PM', pickupTime='4:00 PM', pickupTime='8:00PM'}, {pickupTime='4:00 PM', pickupTime='7:00PM', pickupTime='5:30 PM'}] 

这就是我在 Apps 脚本中用来格式化它们的方法。

 for(var k = 0 ; k < abc.length ; k++){
  let singleDelivery = sourceRange[abc[k]];
  let pickTime = new Date(singleDelivery[8])
  let pickTime2 = Utilities.formatDate(pickTime, "EST", 'h:mm a');
  let dropTime = new Date(singleDelivery[10]);
  let dropTime2 = Utilities.formatDate(dropTime, "EST", 'h:mm a');

  let deliveryDetailsArray = {
    "orderName": singleDelivery[1],
    "driverName": singleDelivery[2],
    "deliveryDate" : singleDelivery[7],
    "pickupTime": pickTime2,
    "dropoffTime": dropTime2,
    "pickUpAddress": singleDelivery[11],
    "dropoffAddress": singleDelivery[12],
    "routingType": singleDelivery[13]
  }      

      deliveryDetails.push(deliveryDetailsArray);

    
     sorted = deliveryDetails.sort((a, b) => a.pickupTime - b.pickupTime)


} 

在声明 devlieryDetailsArray 时不要格式化日期,将其保留为 pickTime 原始日期对象(从你的代码中我不确定它是一个常规的 JS 日期,但是我想是的)。

排序,稍后再格式化。

const sorted = deliveryDetails.sort((a,b) => a.pickupTime - b.pickupTime);
const formattedDeliveryDetails = sorted.map(deliveryDetail => ({...deliveryDetail, pickupTime: Utilities.formatDate(deliveryDetail.pickupTime, "EST", 'h:mm a') }));