【问题标题】:How to convert a number to time?如何将数字转换为时间?
【发布时间】:2020-02-21 13:23:14
【问题描述】:

我正在尝试使用 date-fns 版本 1.30.1 或纯 JavaScript 创建一个接受数字并返回时间戳 (HH:mm) 的函数。

我想要实现的是在输入时间时帮助用户。当用户离开输入字段时,我正在使用 Vue.js 更新字段。因此,如果用户键入 21 然后离开,该字段将理想地更新为 21:00。

一些例子是:

21 = 21:00  
1 = 01:00  
24 = 00:00  
2115 = 21:15  

像 815 这样的数字不必返回 08:15。像 7889 这样的数字应该会返回错误。

我尝试过使用正则表达式:

time = time
    .replace(/^([1-9])$/, '0$1')
    .replace(/^([0-9]{2})([0-9]+)$/, '$1:$2')
    .replace(/^24/, '00:00')

我也尝试过在 date-fns 中使用 parse 方法,但似乎无法解决这个问题。

【问题讨论】:

  • 您能否详细说明您要达到的目标?您可能正在尝试重新发明轮子?请添加操作系统、编程语言等详细信息。
  • 您希望7889 得到什么结果?
  • @sarlacii 我更新了我想要实现的目标。至于语言,这不是标签的用途吗?我没有在这里发布很多问题,所以很抱歉这个愚蠢的问题。
  • @georg 已将您的电话号码添加到帖子中,感谢您指出这一点。

标签: javascript string date time date-fns


【解决方案1】:

基于<100(仅小时)和>=100(100*小时+分钟)的转换,加上一些与24 和一位数(小时和分钟)的斗争:

function num2time(num){
  var h,m="00";
  if(num<100)
    h=num;
  else {
    h=Math.floor(num/100);
    m=("0"+(num%100)).slice(-2);
  }
  h=h%24;
  return ("0"+h).slice(-2)+":"+m;
}

console.log(num2time(8));
console.log(num2time(801));
console.log(num2time(24));
console.log(num2time(2401));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));

原始答案,仅用于评论,但不能正确处理 24 或个位数分钟:

例如你可以做一个非常机械的转换

function num2time(num){
  if(num<10)
    t="0"+num+":00";
  else if(num<100)
    t=num+":00";
  else {
    if(num<1000)
      t="0"+Math.floor(num/100);
    else if(num<2400)
      t=Math.floor(num/100)
    else
      t="00";
    t+=":"+(num%100);
  }
  return t;
}

console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));

示例验证:

function num2time(num){
  var h,m="00";
  if(num<100)
    h=num;
  else {
    h=Math.floor(num/100);
    m=("0"+(num%100)).slice(-2);
  }
  if(h<0 || h>24) throw "Hour must be between 0 and 24"
  if(m<0 || m>59) throw "Minute must be between 0 and 59"
  h=h%24;
  return ("0"+h).slice(-2)+":"+m;
}

var numstr=prompt("Enter time code");
while(true) {
  try {
    console.log(num2time(numstr));
    break;
  } catch(ex) {
    numstr=prompt("Enter time code, "+numstr+" is not valid\n"+ex);
  }
}

【讨论】:

  • 我认为除了添加冒号之外,如果用户键入 2115,它会执行所有操作,它只返回第一个数字 21。
  • @wiu753 我没有看到它没有添加冒号。将代码包装成一个 sn-p(之前不能这样做,我在移动设备上)。
  • 效果很好。我认为最后一个问题是 24 必须转换为 00:00。
  • @wiu753 抱歉,我在交换帖子中的部分时可能有点困惑。所以现在帖子前半部分的代码被认为是解决方案(它也解决了24),而下半部分只是出于“历史原因”。
  • 啊,我明白我在哪里弄糊涂了。这可以做所有事情,还有更多,谢谢。我想知道如果用户以错误的方式输入分钟,您是否对如何处理有任何意见。例如输入 65 而不是 55。
【解决方案2】:

DateFns 实施

恕我直言,添加和删除分钟和小时是管理此转换的一种更简洁的方法:

function formattedTime(val) {
  let helperDate; 
  if(val.length <= 2) {
   if(val > 24)return 'error';       
   helperDate = dateFns.addHours(new Date(0), val-1);   
   return dateFns.format(helperDate, 'HH:mm');
  }
  if(val.length > 2) {
   let hhmm = val.match(/.{1,2}/g);
   if(hhmm[0] > 24 || hhmm[1] > 60) return 'error';
   helperDate = dateFns.addHours(new Date(0), hhmm[0]-1);
   helperDate = dateFns.addMinutes(helperDate, hhmm[1]);
   return dateFns.format(helperDate, 'HH:mm');
  }
}

const myArr = [21, 1, 24, 2115, 815];

myArr.forEach(
  val => console.log(formattedTime(val.toString()))
)
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 我看到 2115 在应该是 21:15 的时候转换为 22:15,否则这个效果很好。
  • 已修复,我必须像第一个条件一样从小时数中减去 1
【解决方案3】:

您可以将第一个字符用作小时,将最后一个字符用作分钟,当少于 4 个字符时,您必须填充 0。

当有 1 或 0 字符时,您需要左右填充。
当有 2 或 3 个字符时,您只需向右填充。

time_str = '230'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

time_str = '24'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

time_str = '3'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

time_str = '78'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

【讨论】:

    【解决方案4】:

    版本 1,将小于 100 的任何时间转换为小时

    const num2time = num => {
      if (num < 100) num *=100;
      const [_,hh,mm] = num.toString().match(/(\d{1,2})(\d{2})$/)
      return `${hh.padStart(2,"0")}:${mm}`
    }
    console.log(num2time(8));
    console.log(num2time(2115));
    console.log(num2time(15));
    console.log(num2time("8"));
    console.log(num2time("2115"));

    如果数字始终代表有效的 (h)hmm,则可以使用版本 2

    const num2time = num => num.toString().replace(/(\d{1,2})(\d{2})$/,"$1:$2");
    
    console.log(num2time(815));
    console.log(num2time(2115));
    console.log(num2time("2115"));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多