当前时间,最接近半小时,下一小时的时间

时间:2019-07-10 10:49:16

标签: javascript

我有两个文本框,其值可设置开始时间和结束时间。如果用户选择了这些时间,则将显示这些值。但是,如果用户正在创建新约会,则默认情况下,它应显示与当前约会最接近的半小时时间,结束时间应为下一小时。

例如,

当前时间是4:37 PM,那么开始时间应该是5:00 PM,结束时间应该是6:00 PM 如果当前时间是7:31 AM,那么开始时间应该是8:00 AM,结束时间应该是9:00 AM。 如果当前时间为11:45 AM,则开始时间应为12:00 PM,结束时间应为01:00 PM

2 个答案:

答案 0 :(得分:0)

我对示例进行了一些更新,以便当用户在8:00设置为8:00时,接下来的30分钟(您可以很容易地更改)就可以了

这种方法的缺点是将8:30设置为9:00,而您可能会争辩说8:30同样有效,因为间隔为30分钟

The push refers to repository [docker.io/joesan/my-image]
2c69d2eb093b: Preparing
d2f0b6dea592: Preparing
197c666de9dd: Preparing
cf5b3c6798f7: Preparing
denied: requested access to the resource is denied
window.addEventListener('load', function() {
  const startElement = document.querySelector('#startTime');
  const endElement = document.querySelector('#endTime');
  const detailsElement = document.querySelector('#appointment_details');
  
  function createTimeString( hours, minutes ) {
    if (hours < 0 || minutes < 0) {
      throw 'argument exception';
    }
    console.log( 'original input ' + hours + ':' + minutes );
    while (parseInt(hours) >= 24) hours = +hours - 24;
    while (parseInt(minutes) >= 60) {
      minutes = +minutes - 60;
      hours = +hours + 1;
    }
    return hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0');
  }

  function handleStartTimeChanged( e ) {
    const timeValue = e.target.value;
    let [hours,minutes] = timeValue.split(':');
    if (Math.round( parseInt( minutes ) / 60.0) === 1) {
      hours = parseInt(hours) + 1;
      minutes = 0;
    } else if (parseInt( minutes ) !== 0) {
      // anything else is same hour but 30 minutes past
      minutes = 30;
    }
    setAppointmentDetails( createTimeString( hours, minutes ), createTimeString( +hours + 1, minutes ) );
  }

  function handleEndTimeChanged( e ) {
    const timeValue = e.target.value;
    let [hours,minutes] = timeValue.split(':');
    if (Math.round( parseInt( minutes ) / 60.0) === 1) {
      hours = parseInt(hours) + 1;
      minutes = 0;
    } else if (parseInt( minutes ) !== 0) {
      // anything else is same hour but 30 minutes past
      minutes = 30;
    }
    setAppointmentDetails( createTimeString( hours - 1, minutes ), createTimeString( hours, minutes ) );
  }
  
  function setAppointmentDetails( startTime, endTime ) {
    detailsElement.innerHTML = `${startTime} till ${endTime}`;
  }

  startElement.addEventListener('change', handleStartTimeChanged );
  endElement.addEventListener('change', handleEndTimeChanged );

} );

答案 1 :(得分:0)

这涉及一些相当简单的计算,并且Math.ceil

const secsPerHalfHour = 1000 * 60 * 30

const nextHalfHour = () => 
  new Date (Math .ceil (new Date() .getTime() / secsPerHalfHour) * secsPerHalfHour)

const next90Mins = () => 
  new Date (Math .ceil ((new Date() .getTime() / secsPerHalfHour) + 2) * secsPerHalfHour)


console .log (`start: ${nextHalfHour()}`)
console .log (`end: ${next90Mins()}`)