如何使用ISO日期格式获取距今天最近的日期?

时间:2019-06-09 05:46:31

标签: javascript typescript

我有一个函数,可以读取对象数组并查找:

  1. 如果customerAuthorizedTimenull

  2. 如果customerAuthorizedTime **is**为空,则找到与今天(即今天)最近的日期。

我的尝试: 我尝试滤除所有对象以查找所有customerAuthorizedTime的尝试为空,然后找到最接近的日期

const filteredData = data.filter((a: MemberAppointment) => a.customerAuthorizedTime === null)
const filteredAppointment = // use .sort() or .find() to find closest date?

我暂时停下来,因为我不确定如何找到最接近当前日期的ISO日期。

我的第二次尝试: 我想尝试对.find()执行更直接的方法:

const currentDate = new Date().toISOString()
const filteredAppointment = data.find((a: MemberAppointment) => a.customerAuthorizedTime === null && // date is closest to today's date)

但是问题仍然是,我不确定如何以ISO格式查找与今天的日期最接近的日期。是否有一种方法也可以通过moment.js满足此条件?

我的数据集:

const data = [
  {
    'appointmentId': 403749,
    'masterAppointmentId': 403749,
    'memberPartyRoleId': 1262903,
    'description': 'Training (30 minutes)',
    'startTime': '2019-06-09T22:00:00-04:00',
    'mustCancelBy': '2019-06-09T22:00:00-04:00',
    'activityTransactionId': 19726389,
    'customerAuthorizedTime': '2019-06-09T00:33:02-04:00',
  },
  {
    'appointmentId': 403750,
    'masterAppointmentId': 403750,
    'memberPartyRoleId': 1262903,
    'description': 'Training (30 minutes)',
    'startTime': '2019-06-09T21:00:00-04:00',
    'mustCancelBy': '2019-06-09T21:00:00-04:00',
    'activityTransactionId': 19726390,
    'customerAuthorizedTime': null,
  },
  {
    'appointmentId': 403748,
    'masterAppointmentId': 403748,
    'memberPartyRoleId': 1262903,
    'description': 'Training (30 minutes)',
    'startTime': '2019-06-09T20:00:00-04:00',
    'mustCancelBy': '2019-06-09T20:00:00-04:00',
    'activityTransactionId': 19726388,
    'customerAuthorizedTime': null,
  },
  {
    'appointmentId': 403747,
    'masterAppointmentId': 403747,
    'memberPartyRoleId': 1262903,
    'description': 'Training (30 minutes)',
    'startTime': '2019-06-09T19:00:00-04:00',
    'mustCancelBy': '2019-06-09T19:00:00-04:00',
    'activityTransactionId': 19726387,
    'customerAuthorizedTime': '2019-06-09T00:13:18-04:00',
  }]

1 个答案:

答案 0 :(得分:0)

遍历所有约会,并计算最近的日期时间(将来)。如果没有项目(数组为空)或所有项目都有customerAuthorizedTime == null-函数的结果将为当前日期时间。

function dateOfClosestApointmentToToday(items)
{
    let now = (new Date()).getTime();
    let found = null; 
    items.filter(function(itm) {
        if (!!itm.customerAuthorizedTime) {
            let t = (new Date(itm.customerAuthorizedTime)).getTime();
            if (!found || t > now && t < found) {
                found = t;
            }
        }
    });
    return (new Date(!!found? found: now)).toISOString(); 
}

//
// get closest datetime
//
let closest = dateOfClosestApointmentToToday(data);