2014-12-24 4 views
0

У меня есть поле ввода:Формат строки в формат времени, как чч: мм

<input id="szReminderTime" type="text" value="" maxlength="5" 
    onblur="format_reminder_time(this.value);" 
    name="askForQuoteAry[szReminderTime]" /> 

Формат Time поля hh:mm на 24-часовом, например, 7:30, 11:45, 16:10, 19:11, 22:43.

Если типы операторского период (11.45), запятая (11,45), пространство (11 45), тир (11-45), или ничего (1145 или 945), то каждый из них следует рассматривать, чтобы иметь То же значение. Затем, как только оператор покидает поле, значение должно быть показано двоеточием, то есть 11:45 или 9:45.

Для этого я использовал следующую функцию JavaScript, которая отлично подходит для меня, но может ли кто-нибудь оптимизировать мой код, поскольку мой код не выглядит приятным для меня?

+0

по теме (см codereview.stackexchange.com), и вы даже не разместить код – Alnitak

+0

Где находится "нижеследующий код"? – RobG

+0

Этот вопрос не является дубликатом [* как форматировать дату javascript *] (http://stackoverflow.com/questions/3552461/how-to-format-javascript-date). Объект даты или даты не задействован, ОП спрашивает, как переформатировать строку, представляющую время. – RobG

ответ

1

Если это всего лишь одно место для формирования даты, я бы предложил вам использовать plain javascipt для форматирования.

Если нет http://momentjs.com/, это решение для большинства вопросов, связанных с датированием.

moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago 

http://momentjs.com/docs/#/displaying/

для примера было бы просто "hh:mm", как у вас в описании.

+0

Думайте, что 'moment.js' является немного излишним, чего хочет OP. :-) – 0x2D9A3

+0

Для этого требуется, чтобы OP определял, какой формат струны обрабатывается (например, hh: mm, h.mm, h, mm, hhmm), затем имеет отдельный вызов moment.js для каждого из них. Функция, которая должна выполняться по требованию OP, составляет всего 6 строк кода, что, вероятно, меньше, чем требуется для различных вызовов moment.js (и вообще не требует библиотеки). – RobG

+0

Как я уже говорил, простой javascript лучше, если это один таймер, но по внешнему виду он использует много материала даты. Итак, решение @robG лучше выбрать, чем любой lib, если он является onetimer. –

0

Функция, предназначенная для преобразования 24 часов в 12 часов, довольно проста, однако у вас есть особые требования. Рассмотрим следующий пример:

// Convert string in 24 hour time to 12 hour hh:mm ap 
// Input can be 12:23, 945, 09,12, etc. 
function from24to12(s) { 
    var b = s.replace(/\D/g,''); 
    var h = b.substring(0, b.length - 2); 
    var m = b.substring(b.length - 2); 
    return (h%12 || 12) + ':' + m + ' ' + (h>11? 'PM':'AM'); 
} 

console.log(from24to12('23:15')); // 11:15 PM 
console.log(from24to12('015')); // 12:15 AM 
console.log(from24to12('1.15')); // 1:15 AM 

Это предполагает, что вы не хотите, ведущие нули на час, и что оператор всегда будет ключ из двух цифр для минут, например, 9.03, а не 9.3. Для поддержки последнего требуется еще 3 строки кода.

Следующая поддерживает любой символ для сепаратора, а также сказать 9.3 для 9:03 AM:

// Convert string in 24 hour time to 12 hour hh:mm ap 
// Input can be 12:23, 945, 09,12, etc. 
// Sseparator can be any non-digit. If no separator, assume [h]hmm 
function from24to12(s) { 
    function z(n){return (n<10?'0':'')+n} 
    var h, m, b, re = /\D/; 

    // If there's a separator, split on it 
    // First part is h, second is m 
    if (re.test(s)) { 
    b = s.split(re); 
    h = b[0]; 
    m = z(+b[1]); 

    // Otherwise, last two chars are mm, first one or two are h 
    } else { 
    h = s.substring(0, s.length - 2); 
    m = s.substring(s.length - 2); 
    } 
    return (h%12 || 12) + ':' + m + ' ' + (h>11? 'PM':'AM'); 
} 

console.log(from24to12('23:15')); // 11:15 AM 
console.log(from24to12('005')); // 12:05 AM 
console.log(from24to12('1.15')); // 1:15 AM 
console.log(from24to12('17.5')); // 5:05 PM 
0

Вы могли бы сделать это в JavaScript, довольно легко. Вы можете расширить это, чтобы соответствовать вашим требованиям. Пожалуйста, обратите внимание на мой сценарий:

Date.prototype.dateToday = function (syntax) { 
    var dateToday = null; 

    if (syntax === 'dd-mm-yyyy') { 
     dateToday = (
     ((this.getDate() < 10) ? '0' + this.getDate() : this.getDate()) + '-' + ((this.getMonth() + 1 < 10) ? '0' + this.getMonth() : this.getMonth()) + '-' + this.getFullYear()); 

    } else if (syntax === 'dd/mm/yyyy') { 
     dateToday = (
     ((this.getDate() < 10) ? '0' + this.getDate() : this.getDate()) + '/' + ((this.getMonth() + 1 < 10) ? '0' + this.getMonth() : this.getMonth()) + '/' + this.getFullYear()); 

    } else if (syntax === 'dd-mm-yy') { 
     var year = this.getFullYear().toString(); 

     dateToday = (
     ((this.getDate() < 10) ? '0' + this.getDate() : this.getDate()) + '-' + ((this.getMonth() + 1 < 10) ? '0' + this.getMonth() : this.getMonth()) + '-' + year.substr(2, 4)); 

    } else if (syntax === 'dd/mm/yy') { 
     var year = this.getFullYear().toString(); 

     dateToday = (
     ((this.getDate() < 10) ? '0' + this.getDate() : this.getDate()) + '/' + ((this.getMonth() + 1 < 10) ? '0' + this.getMonth() : this.getMonth()) + '/' + year.substring(2,4)); 
    } 

    return dateToday; 

}; 

Date.prototype.timeNow = function (syntax) { 
    var timeNow = null; 

    if (syntax === 'hh:mm:ss') { 
     timeNow = (
     ((this.getHours() < 10) ? '0' + this.getHours() : this.getHours()) + ':' + ((this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes()) + ':' + ((this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds())); 
    } else if (syntax === 'hh:mm') { 
     timeNow = (
     ((this.getHours() < 10) ? '0' + this.getHours() : this.getHours()) + ':' + ((this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes()) + ':' + ((this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds())); 

    } else { 
     timeNow = (
     ((this.getHours() < 10) ? '0' + this.getHours() : this.getHours()) + ':' + ((this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes()) + ':' + ((this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds()) + '.' + ((this.getMilliseconds() < 10) ? '0' + this.getMilliseconds() : this.getMilliseconds())); 

    } 

    return timeNow; 
} 

Date.prototype.hourNow = function() { 
    var hours = ((this.getHours() < 10) ? '0' + this.getHours() : this.getHours()); 
    return hours; 
} 

Date.prototype.minuteNow = function() { 
    var minutes = ((this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes()); 
    return minutes 
}; 

Date.prototype.secondNow = function() { 
    var seconds = ((this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds()); 
    return seconds; 
}; 

Date.prototype.milisecondsNow = function() { 
    var milliseconds = ((this.getMilliseconds() < 10) ? '0' + this.getMilliseconds() : this.getMilliseconds()); 
    return milliseconds; 
}; 

Или взгляните на мой Git для этого помощника: datehelper.js

Смежные вопросы