development

자바 스크립트를 사용하여 24 시간 시간을 오전 및 오후 12 시간 시간으로 변환

big-blog 2020. 12. 13. 10:10
반응형

자바 스크립트를 사용하여 24 시간 시간을 오전 및 오후 12 시간 시간으로 변환


다음 JSON 반환 값을 24 시간 형식에서 오전 및 오후 12 시간 형식으로 변환하는 가장 좋은 방법은 무엇입니까? 날짜는 동일하게 유지되어야합니다. 서식을 지정해야하는 유일한 것은 시간입니다.

February 04, 2011 19:00:00

추신 : jQuery를 사용하면 더 쉬워집니다! 또한 간단한 함수 / 코드를 선호하고 Date.js를 사용하지 않습니다.


업데이트 2 : 초 옵션없이

업데이트 : 정오 이후 오전 수정, 테스트 : http://jsfiddle.net/aorcsik/xbtjE/

이 기능을 만들었습니다.

function formatDate(date) {
  var d = new Date(date);
  var hh = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  var dd = "AM";
  var h = hh;
  if (h >= 12) {
    h = hh - 12;
    dd = "PM";
  }
  if (h == 0) {
    h = 12;
  }
  m = m < 10 ? "0" + m : m;

  s = s < 10 ? "0" + s : s;

  /* if you want 2 digit hours:
  h = h<10?"0"+h:h; */

  var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);

  var replacement = h + ":" + m;
  /* if you want to add seconds
  replacement += ":"+s;  */
  replacement += " " + dd;

  return date.replace(pattern, replacement);
}

alert(formatDate("February 04, 2011 12:00:00"));


다음은 if 문없이 시간을 변경할 수있는 방법입니다.

hours = ((hours + 11) % 12 + 1);

    //it is pm if hours from 12 onwards
    suffix = (hours >= 12)? 'pm' : 'am';

    //only -12 from hours if it is greater than 12 (if not back at mid night)
    hours = (hours > 12)? hours -12 : hours;

    //if 00 then it is 12 am
    hours = (hours == '00')? 12 : hours;

출력에서 시간만을 원하는 사람을 위해 JavaScript의 Date :: toLocaleString () 메서드에 옵션을 전달할 수 있습니다. 예:

var date = new Date("February 04, 2011 19:00:00");
var options = {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);

timeString은 다음과 같이 설정됩니다.

오전 8시

초를 원하는 경우 옵션에 "초 : '숫자'"를 추가하십시오. 모든 옵션은 이것을 참조 하십시오 .


프로토 타입을 사용하여 합리적으로 간결하게 수행하는 방법은 다음과 같습니다.

Date.prototype.getFormattedTime = function () {
    var hours = this.getHours () == 0? "12": this.getHours ()> 12? this.getHours ()-12 : this.getHours ();
    var minutes = (this.getMinutes () <10? "0": "") + this.getMinutes ();
    var ampm = this.getHours () <12? "오전 오후";
    var formattedTime = 시간 + ":"+ 분 + ""+ ampm;
    formattedTime 반환;
}

그런 다음 문자열 값을 날짜로 변환하고 새로운 방법을 사용하기 만하면됩니다.

var stringValue = "2011 년 2 월 4 일 19:00:00;
var dateValue = new Date (stringValue);
var formattedTime = dateValue.getFormattedTime ();

또는 한 줄로 :

var formattedTime = new Date ( "2011 년 2 월 4 일 19:00:00"). getFormattedTime ();

간단하고 깔끔하게 유지하세요

var d = new Date();
var n = d.toLocaleString();

https://jsfiddle.net/rinu6200/3dkdxaad/#base


function pad(num) {return ("0" + num).slice(-2);}
function time1() {
  var today = new Date(),
    h = today.getHours(),
    m = today.getMinutes(),
    s = today.getSeconds();
    
  h = h % 12;
  h = h ? h : 12; // the hour '0' should be '12'
  clk.innerHTML = h + ':' + 
    pad(m) + ':' + 
    pad(s) + ' ' + 
    (h >= 12 ? 'PM' : 'AM');
}
window.onload = function() {
  var clk = document.getElementById('clk');
  t = setInterval(time1, 500);
}
<span id="clk"></span>


jQuery에는 날짜 유틸리티가 전혀 없습니다. 추가 라이브러리를 사용하지 않는 경우 일반적인 방법은 JavaScript Date개체를 만든 다음 여기에서 데이터를 추출하여 직접 형식을 지정하는 것입니다.

Date객체 를 생성하기 위해 JSON의 날짜 문자열이 Date이해 하는 형식 (IETF 표준 (기본적으로 RFC 822 섹션 5 ))인지 확인할 수 있습니다. 따라서 JSON을 변경할 기회가 있다면 가장 쉬울 것입니다. (편집 : 형식이 실제로 그대로 작동 할 수 있습니다.)

JSON을 변경할 수없는 경우 문자열을 직접 구문 분석하고 일, 입, 연도, 시간, 분 및 초를 정수로 가져 와서 Date객체를 만들어야합니다 .

당신이 당신의 일단 Date개체를 당신은 당신이 필요로하는 데이터를 추출하고 포맷해야합니다 :

   var myDate = new Date("4 Feb 2011, 19:00:00");
   var hours = myDate.getHours();
   var am = true;
   if (hours > 12) {
      am = false;
      hours -= 12;
   } else (hours == 12) {
      am = false;
   } else (hours == 0) {
      hours = 12;
   }

   var minutes = myDate.getMinutes();
   alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);

당신은 이것을 볼 수 있습니다 . 예 중 하나는 다음과 같습니다.

var d = new Date(dateString);

Date 객체가 있으면 상당히 쉽게 재생할 수 있습니다. toLocaleDateString, toLocaleTimeString을 호출하거나 getHours가 12보다 큰지 테스트 한 다음 AM / PM 시간을 계산할 수 있습니다.


date = date.replace(/[0-9]{1,2}(:[0-9]{2}){2}/, function (time) {
    var hms = time.split(':'),
        h = +hms[0],
        suffix = (h < 12) ? 'am' : 'pm';
    hms[0] = h % 12 || 12;        
    return hms.join(':') + suffix
});

편집 : 오전 12시 / 오후 처리하는 것을 잊었습니다. 결정된.


1) 24 시간 만들기에 대한 "제곱"지침이 12 시간이되었습니다.

var hours24 = new Date().getHours(); // retrieve current hours (in 24 mode)
var dayMode = hours24 < 12 ? "am" : "pm"; // if it's less than 12 then "am"
var hours12 = hours24 <= 12 ? (hours24 == 0 ? 12 : hours24) : hours24 - 12;
// "0" in 24-mode now becames "12 am" in 12-mode – thanks to user @Cristian
document.write(hours12 + " " + dayMode); // printing out the result of code

2) 한 줄에서 (약간 다른 알고리즘으로 동일한 결과) :

var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");

두 옵션 모두 문자열 등의 반환 "5 pm"또는 "10 am"


 function GetTime(date) {
        var currentTime = (new Date(date))
        var hours = currentTime.getHours()
        //Note: before converting into 12 hour format
        var suffix = '';
        if (hours > 11) {
            suffix += "PM";
        } else {
            suffix += "AM";
        }
        var minutes = currentTime.getMinutes()
        if (minutes < 10) {
            minutes = "0" + minutes
        }
        if (hours > 12) {
            hours -= 12;
        } else if (hours === 0) {
            hours = 12;
        }
        var time = hours + ":" + minutes + " " + suffix;
        return time;
    }

아래 코드로 시도하십시오

var s = "15 Feb 2015 11.30 a.m";
        var times = s.match("((([0-9])|([0-2][0-9])).([0-9][0-9])[\t ]?((a.m|p.m)|(A.M|P.M)))");            
        var time = "";

        if(times != null){                          
            var hour = times[2];
            if((times[6] == "p.m" || times[6] == "P.M")){
                if(hour < 12){
                    hour = parseInt(hour) + parseInt(12);
                }else if(hour == 12){
                    hour = "00";
                }
            }
            time = [hour, times[5], "00"].join(":");

        }

감사


var dt = new Date();
    var h =  dt.getHours(), m = dt.getMinutes();
    var thistime = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
console.log(thistime);

다음은 데모입니다.


이것은 나를 위해 일했습니다!

function main() {
  var time = readLine();
  var formattedTime = time.replace('AM', ' AM').replace('PM', ' PM');
  var separators = [':', ' M'];
  var hms = formattedTime.split(new RegExp('[' + separators.join('') + ']'));
  if (parseInt(hms[0]) < 12 && hms[3] == 'P')
      hms[0] = parseInt(hms[0]) + 12;
  else if (parseInt(hms[0]) == 12 && hms[3] == 'A')
      hms[0] = '00';
  console.log(hms[0] + ':' + hms[1] + ':' + hms[2]);

}

나는 상대적인 초보자이지만 여기에 내 프로젝트 중 하나를 위해 생각해 낸 것이 있으며 작동하는 것 같습니다. 더 간단한 방법이있을 수 있습니다.

function getTime() {
    var nowTimeDate = new Date();
    var nowHour = nowTimeDate.getHours();
    var nowMinutes = nowTimeDate.getMinutes();
    var suffix = nowHour >= 12 ? "pm" : "am";
    nowHour = (suffix == "pm" & (nowHour > 12 & nowHour < 24)) ? (nowHour - 12) : nowHour;
    nowHour = nowHour == 0 ? 12 : nowHour;
    nowMinutes = nowMinutes < 10 ? "0" + nowMinutes : nowMinutes;
    var currentTime = nowHour + ":" + nowMinutes + suffix;
    document.getElementById("currentTime").innerHTML = currentTime;
}

이것은 오전 / 오후를 사용하여 24 시간 형식을 12 시간으로 변환하는 함수를 호출하는 HTML 코드입니다.

<pre id="tests" onClick="tConvert('18:00:00')">
  test on click 18:00:00
</pre>
<span id="rzlt"></span>

이제 js 코드 에서이 tConvert 함수를 그대로 작성하십시오.

 function tConvert (time)
  {
     
   // Check correct time format and split into components
   time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

    if (time.length > 1) 
    { // If time format correct
        
      time = time.slice (1);  // Remove full string match value
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    //return time; // return adjusted time or original string
      var tel = document.getElementById ('rzlt');
      
      tel.innerHTML= time.join ('');
  }

나를 위해 일하는 18:00:00에서 6:00:00 PM으로 변환


이 기능은 양방향으로 변환됩니다 : 12 ~ 24 시간 또는 24 ~ 12 시간

function toggle24hr(time, onoff){
    if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
    var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
    time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
    time[0] = Number(time[0])
    if(onoff){//convert to 24 hour:
        if((pm && time[0]!=12)) time[0] += 12
        else if(!pm && time[0]==12) time[0] = '00'  //handle midnight
        if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
    }else{ //convert to 12 hour:
        pm = time[0]>=12
        if(!time[0]) time[0]=12 //handle midnight
        else if(pm && time[0]!=12) time[0] -= 12
    }
    return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}

다음은 몇 가지 예입니다.

//convert to 24 hour:
toggle24hr('12:00am')   //returns 00:00
toggle24hr('2:00pm')    //returns 14:00
toggle24hr('8:00am')    //returns 08:00
toggle24hr('12:00pm')   //returns 12:00

//convert to 12 hour:
toggle24hr('14:00')    //returns 2:00pm
toggle24hr('08:00')    //returns 8:00am
toggle24hr('12:00')    //returns 12:00pm
toggle24hr('00:00')    //returns 12:00am

//you can also force a specific format like this:
toggle24hr('14:00',1)    //returns 14:00
toggle24hr('14:00',0)    //returns 2:00pm

여기 있습니다

var myDate = new Date("February 04, 2011 19:00:00");
var hr = myDate.getHours(); 
var convHrs = "";
var ampmSwitch = "";
ampmSwitch = (hr > 12)? "PM":"AM"; 
convHrs = (hr >12)? hr-12:hr;
// Build back the Date / time using getMonth/ getFullYear and getDate and other functions on the myDate object. Enclose it inside a func and there you got the working 12 hrs converter ;)

그리고 여기 yas를위한 변환기 func가 있습니다;) 행복한 코딩 !!

function convertTo12Hrs(yourDateTime){
    var myDate = new Date(yourDateTime);
    var dtObject = new Object();
    var monthsCollection = {0:"January", 1:"February",2:"March",3:"April",4:"May",5:"June",6:"July",7:"August",8:"September",9:"October",10:"November",11:"December"};
    dtObject.year = myDate.getFullYear();
    dtObject.month = monthsCollection[myDate.getMonth()];
    dtObject.day = (myDate.getDate()<10)?"0"+myDate.getDate():myDate.getDate();
    dtObject.minutes = (myDate.getMinutes() < 10)? "0"+myDate.getMinutes():myDate.getMinutes();
    dtObject.seconds = (myDate.getSeconds() < 10)? "0"+myDate.getSeconds():myDate.getSeconds();
    // Check if hours are greater than 12? Its PM
    dtObject.ampmSwitch = (myDate.getHours() > 12)? "PM":"AM";
    // Convert the hours
    dtObject.hour = (myDate.getHours() > 12)?myDate.getHours()-12:myDate.getHours();
    // Add the 0 as prefix if its less than 10
    dtObject.hour = (dtObject.hour < 10)? "0"+dtObject.hour:dtObject.hour;

    // Format back the string as it was or return the dtObject object or however you like. I am returning the object here
    return dtObject;
}

invoke it like convertTo12Hrs("February 04, 2011 19:00:00"); it will return you the object, which in turn you can use to format back your datetime string as you fancy...


You're going to end up doing alot of string manipulation anyway, so why not just manipulate the date string itself?

Browsers format the date string differently.

Netscape ::: Fri May 11 2012 20:15:49 GMT-0600 (Mountain Daylight Time)

IE ::: Fri May 11 20:17:33 MDT 2012

so you'll have to check for that.

var D = new Date().toString().split(' ')[(document.all)?3:4];

That will set D equal to the 24-hour HH:MM:SS string. Split that on the colons, and the first element will be the hours.

var H = new Date().toString().split(' ')[(document.all)?3:4].split(':')[0];

You can convert 24-hour hours into 12-hour hours, but that hasn't actually been mentioned here. Probably because it's fairly CRAZY what you're actually doing mathematically when you convert hours from clocks. In fact, what you're doing is adding 23, mod'ing that by 12, and adding 1

twelveHour = ((twentyfourHour+23)%12)+1;

So, for example, you could grab the whole time from the date string, mod the hours, and display all that with the new hours.

var T = new Date().toString().split(' ')[(document.all)?3:4].split(':');
T[0] = (((T[0])+23)%12)+1;
alert(T.join(':'));

With some smart regex, you can probably pull the hours off the HH:MM:SS part of the date string, and mod them all in the same line. It would be a ridiculous line because the backreference $1 couldn't be used in calculations without putting a function in the replace.

Here's how that would look:

var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/,function(){return ((parseInt(RegExp.$1)+23)%12)+1} );

Which, as I say, is ridiculous. If you're using a library that CAN perform calculations on backreferences, the line becomes:

var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/, (($1+23)%12)+1);

And that's not actually out of the question as useable code, if you document it well. That line says:

Make a Date string, break it up on the spaces, get the browser-apropos part, and replace the first two-digit-number with that number mod'ed.

Point of the story is, the way to convert 24-hour-clock hours to 12-hour-clock hours is a non-obvious mathematical calculation:

You add 23, mod by 12, then add one more.


Here is a nice little function that worked for me.

function getDisplayDatetime() {
    var d = new Date(); var hh = d.getHours(); var mm = d.getMinutes(); var dd = "AM"; var h = hh;

    if (mm.toString().length == 1) {
        mm = "0" + mm;
    }

    if (h >= 12) {
        h = hh - 12;
        dd = "PM";
    }

    if (h == 0) {
        h = 12;
    }
    var Datetime = "Datetime: " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getUTCDate() + " " + h + ":" + mm;
    return Datetime + " " + dd;
}

I noticed there is already an answer, but I wanted to share my own solution, using pure JavaScript:

function curTime(pm) {
  var dt = new Date();
  var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
  var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
  return time;
}

You can see it in action at https://jsfiddle.net/j2xk312m/3/ using the following code block:

(function() {

  function curTime(pm) {
    var dt = new Date();
    var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
    var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : ""); 
    return time;
  }

  alert("12-hour Format:    "+curTime(true)+"\n24-hour Format:    "+curTime(false));

})();

You could try this more generic function:

function to12HourFormat(date = (new Date)) {
  return {
    hours: ((date.getHours() + 11) % 12 + 1),
    minutes: date.getMinutes(),
    meridian: (date.getHours() >= 12) ? 'PM' : 'AM',
  };
}

Returns a flexible object format.

https://jsbin.com/vexejanovo/edit

참고URL : https://stackoverflow.com/questions/4898574/converting-24-hour-time-to-12-hour-time-w-am-pm-using-javascript

반응형