How do I get the time of day in javascript/Node.js? - javascript

I want to get 1 to 24, 1 being 1am Pacific Time.
How can I get that number in Node.JS?
I want to know what time it is in Pacific time right now.

This function will return you the date and time in the following format: YYYY:MM:DD:HH:MM:SS. It also works in Node.js.
function getDateTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var day = date.getDate();
day = (day < 10 ? "0" : "") + day;
return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

You should checkout the Date object.
In particular, you can look at the getHours() method for the Date object.
getHours() return the time from 0 - 23, so make sure to deal with it accordingly. I think 0-23 is a bit more intuitive since military time runs from 0 - 23, but it's up to you.
With that in mind, the code would be something along the lines of:
var date = new Date();
var current_hour = date.getHours();

Check out the moment.js library. It works with browsers as well as with Node.JS. Allows you to write
moment().hour();
or
moment().hours();
without prior writing of any functions.

Both prior answers are definitely good solutions. If you're amenable to a library, I like moment.js - it does a lot more than just getting/formatting the date.

There's native method to work with date
const date = new Date();
let hours = date.getHours();

If you only want the time string you can use this expression (with a simple RegEx):
new Date().toISOString().match(/(\d{2}:){2}\d{2}/)[0]
// "23:00:59"

var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var day = date.getDate();
day = (hour > 12 ? "" : "") + day - 1;
day = (day < 10 ? "0" : "") + day;
x = ":"
console.log( month + x + day + x + year )
It will display the date in the month, day, then the year

For my instance i used it as a global and then called its for a time check of when hours of operation.
Below is from my index.js
global.globalDay = new Date().getDay();
global.globalHours = new Date().getHours();
To call the global's value from another file
/*
Days of the Week.
Sunday = 0, Monday = 1, Tuesday = 2, Wensday = 3, Thursday = 4, Friday = 5, Saturday = 6
Hours of the Day.
0 = Midnight, 1 = 1am, 12 = Noon, 18 = 6pm, 23 = 11pm
*/
if (global.globalDay === 6 || global.globalDay === 0) {
console.log('Its the weekend.');
} else if (global.globalDay > 0 && global.globalDay < 6 && global.globalHours > 8 && global.globalHours < 18) {
console.log('During Business Hours!');
} else {
console.log("Outside of Business hours!");
}

To start your node in PST time zone , use following command in ubuntu.
TZ=\"/usr/share/zoneinfo/GMT+0\" && export TZ && npm start &
Then You can refer Date Library to get the custom calculation date and time functions in node.
To use it client side refer this link, download index.js and assertHelper.js and include that in your HTML.
<script src="assertHelper.js"></script>
<script type="text/javascript" src="index.js"></script>
$( document ).ready(function() {
DateLibrary.getDayOfWeek(new Date("2015-06-15"),{operationType:"Day_of_Week"}); // Output : Monday
}
You can use different functions as given in examples to get custom dates.
If first day of week is Sunday, what day will be on 15th June 2015.
DateLibrary.getDayOfWeek(new Date("2015-06-15"),
{operationType:"Day_Number_of_Week",
startDayOfWeek:"Sunday"}) // Output : 1
If first day of week is Tuesday, what week number in year will be
follow in 15th June 2015 as one of the date.
DateLibrary.getWeekNumber(new Date("2015-06-15"),
{operationType:"Week_of_Year",
startDayOfWeek:"Tuesday"}) // Output : 24
Refer other functions to fulfill your custom date requirements.

Related

Javascript time and date change by timezone difference in hours

I have this code, which is to change the time and date - according to timezone difference for example 5 hours (indicated by /////TIME ZONE DIFFERECEN/////), but it is not working how i would expect it to run; e.g: not changing the date and time when applicable. Can anyone help.
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var months = ["31"];
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
months.push("29");
} else {
months.push("28");
}
monthsappend = ["31", "30", "31", "30", "31", "31", "30", "31", "20", "31"];
months.concat(monthsappend);
time = "7:00pm";
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s?([AaPp][Mm]?)$/)[1];
var pm = ['P', 'p', 'PM', 'pM', 'pm', 'Pm'];
var am = ['A', 'a', 'AM', 'aM', 'am', 'Am'];
if (pm.indexOf(AMPM) >= 0 && hours < 12) hours = hours + 12;
if (am.indexOf(AMPM) >= 0 && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
timearr = [sHours, sMinutes];
timearr[0] += 5;
/////////////////////////////// TIME ZONE DIFFERENCE////////////////////////////
if (time.toLowerCase().includes("pm")) {
}
if (timearr < 0) {
day -= 1;
if (day == 0) {
month -= 1;
if (month == 0) {
month = 12;
year = dateObj.getFullYear() - 1;
}
day = months[month - 1];
}
} else {
if (timearr => 24) {
timearr[0] = 24 - timearr[0];
if (day == months[month - 1]) {
day = 1;
month += 1;
if (month == 12) {
month = 1;
year += 1;
}
}
}
}
newdate = day + "/" + month + "/" + year;
console.log(newdate);
console.log(timearr[0]);
Well, first I'll point out the bugs:
You have an arrow function => instead of a greater-than-or-equal-to operator >= (Thanks RobG).
You treat timearr as both an array, and later as a single number. I think you meant to compare timearr[0].
When you add the 5 hours, you're concatenating strings. "19" + 5 === "195". You need to work with numbers here, not strings.
You forgot to adjust timearr[0] in the first section of the large if statement.
You have subtraction in opposite order when you adjust timearr[0] in the second section of the large if. (24 - 26 === -2, you probably meant 26 - 24 === 2).
At the end, you increment month += 1 before checking if (month == 12). Either that needs to be in an else, or you'd have to check for month === 13.
You're using == in places where === would be more appropriate.
You forgot var when you declared timearr.
You took the current date, but hard-coded the time.
Overall, it looks like you are trying to output the current date, in day/month/year format, at UTC+5. There are many simpler ways to do what you're asking. For example:
// Get the current moment in time, as a Date object.
var d = new Date();
// Add 5 hours of absolute duration. The setter handles the bubbling for you.
// Be sure to use UTC here, to avoid interference from transitions of the local time zone.
d.setUTCHours(d.getUTCHours() + 5);
// Get the properties we want to display.
var year = d.getUTCFullYear();
var month = d.getUTCMonth() + 1;
var day = d.getUTCDate();
// Construct the string for output in the desired format.
var s = day + '/' + month + '/' + year;
Or with Moment.js:
var s = moment().utcOffset(5).format('D/M/YYYY');
Do keep in mind also "Time Zone != Offset". It just so happens that all the places in the world that currently use UTC+5 use it year-round (ex, Pakistan) but if you were talking about US Eastern Time, it would be UTC-5 for some parts of the year, and UTC-4 for other parts of the year.

Date code not working in JS

I bet this is something really silly but I am tired and looking for a quick escape so please indulge me. Objective is to be able to add arbitrary days to a date constructed from a string like 2015-01-01.
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = date.getMonth().toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month + '-' + day;
}
And then :
I get the output which is wrong because I am adding 90 days..
Two dates: 2015-01-01 2015-02-31
The problem lies in this line:
var month = date.getMonth().toString();
The function Date.getMonth() returns “the month (0-11) in the specified date according to local time”. January is 0, December is 11, so you need to add 1 to the output:
var month = "" + (date.getMonth()+1);
var month = date.getMonth().toString(); prints the no of months starting from no 0 so the month number is reduced by 1 for eg. the value of january from date.getMonth(); would be 0 and so on till 11.
here's the correct version for your code
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
console.log("before conversion");
console.log(t1_date);//before conversion
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
console.log("after conversion");
console.log(t1_date);//after conversion
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var month1=(month+1).toString();
month1 = month1.length > 1 ? month1 : '0' + month1;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month1 + '-' + day;
}
Never parse strings with the Date constructor, always manually parse them. An ISO date without a timezone should be treated as local*, however ES5 said to treat it as UTC, then ECMAScript 2015 inferred to treat them as local (hooray for consistency) but then the implementors decided to treat them as UTC again, so browsers might do either (or NaN).
So the sensible thing is to manually parse them as local.
Outputting as a local ISO date is also fairly simple.
* Where local means per system settings.
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
document.write(parseISODate('2015-01-01') + '<br>');
function toISODate(date) {
function z(n){return ('0'+n).slice(-2)}
return date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' + z(date.getDate());
}
document.write(toISODate(parseISODate('2015-01-01')));
To add 90 days, it is simpler to just add 90 days to the date:
var d = new Date(2015,0,1); // 1 January 2015
d.setDate(d.getDate() + 90); // add 90 days
document.write(d.toLocaleString()); // 1 April 2015

How to make JS date respect local timezone?

I have the follow function that properly returns the date in the format required, but the value returned isn't respecting the local timezone. In this case, its 4 hours off. What would I need to modify in this function to make it add the proper offsets based on the users location?
Thanks!
function date_str(seconds) {
var dt = new Date(1970, 0, 1);
dt.setSeconds(seconds);
console.log(dt);
var month = dt.getMonth() + 1;
var date = dt.getDate();
var year = dt.getFullYear();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
return month + '/' + date + '/' + year + ', ' + hours + ':' + minutes + ' ' + ampm;
}
Edit: Passing unix time to function 1396450616.505 which converts to Wed, 02 Apr 2014 14:56:56 GMT which returns Sent at 4/2/2014, 2:56 PM from the function itself. The time here is 10:56 AM EST.
Assuming that seconds is a unix epoch (UTC), you should just use
function date_str(seconds) {
var dt = new Date(seconds*1000);
console.log(dt);
…
instead. The get…() methods will respect the local timezone. If you don't want that, you should use the getUTC…() equivalents.

How can I subtract hours from a HH:MM AM time string in Javascript?

What's the best way to subtract a few hours from a time string formatted as such:
8:32 AM
I thought about splitting the string at the colon but when subtracting 3 hours from, say, 1:00 AM I get -2:00 AM instead of the desired 10:00 PM.
Most reliable method is to convert it into a JS date object, then do you math on that
var olddate = new Date(2011, 6, 15, 8, 32, 0, 0); // create a date of Jun 15/2011, 8:32:00am
var subbed = new Date(olddate - 3*60*60*1000); // subtract 3 hours
var newtime = subbed.getHours() + ':' + subbed.getMinutes();
the Date object accepts either year/month/day/hour/minute/second/milliseconds OR a unix-style timestamp of milliseconds-since-Jan-1-1970 for the constructor.
Using moment.js
moment("8:32 AM", 'h:mm A').subtract('hours', 2).format('h:mm A')
If you just want to play with only the hours, I think the following would be easy for you:
var timeStr = '1:30 PM'
var parts = timeStr.split(':');
var hour = parseInt($.trim(parts[0]));
hour -= 3;
if(hour <= 0){
// easily flip it by adding 12
hour += 12;
// swap am & pm
if(parts[1].match(/(AM|am)/)){
parts[1] = parts[1].replace('AM', 'PM').replace('am', 'pm')
// keep the case
} else {
parts[1] = parts[1].replace('PM', 'AM').replace('pm', 'am')
}
}
// final answer
timeStr = hour + ':' + parts[1];
you can use that peace of code :
var T1=new Date("September 5, 2005 8:10:00");
var T2=new Date("September 5, 2005 13:35:00");
var diff=new Date();
diff.setTime(T2-T1);
alert(diff.getHours()+":"+diff.getMinutes())
hope this helps..
Hardest part is parsing in your time - I've just added Jan 1, 2009 to the start of the parse method so that it parses it nicely and you don't need to write your own. (not that it's difficult). Collapse the code below into a few lines - expanded to show the steps.
<html>
<head>
<script type="text/javascript">
function calculateTime(stringTime) {
var hoursToSubtract = 1;
var oldTime = Date.parse('Jan 1, 2009 ' + stringTime);
var newTime = new Date(oldTime - 1000 * 60 * 60 * hoursToSubtract);
var hours = newTime.getHours();
var minutes = newTime.getMinutes();
var designation = "PM";
if ((hours == 0 || hours == 24) && minutes == 0)
designation = 'MIDNIGHT';
else if (hours == 12 && minutes == 0)
designation = 'NOON'
else if (hours < 12)
designation = 'AM';
else
hours -= 12;
document.write('new time = ' + hours + ':' + minutes + ' ' + designation );
}
</script>
</head>
<body>
<script type="text/javascript">
calculateTime('8:30 AM');
calculateTime('8:30 PM');
calculateTime('12:10 PM');
</script>
</body>
</html>
Lots of answers on the right track, one more to consider:
// Assumes timeString is hh:mm am/pm
function addHours(timeString, h) {
var t = timeString.match(/\d+/g);
var am = /am$/.test(timeString);
var d = new Date();
d.setHours(+t[0] + (am? 0 : 12) + +h, +t[1]);
return formatTime(d.getHours() + ':' + d.getMinutes());
}
function formatTime(t) {
function addZ(n) {
return n<10? '0'+n : ''+n;
}
var t = t.split(':');
var m = (t[0] > 12)? 'pm' : 'am';
return addZ(t[0]%12 || t[0]) + ':' + addZ(t[1]) + ' ' + m;
}
alert( addHours('12:15 am', -13) ); // 11:15 pm
You might try a jQuery library like DateJs. Below are some examples shown from that link:
// Number fun
(3).days().ago();
// Convert text into Date
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

What is the best way to convert the following JSON returned value from a 24-hour format to 12-hour format w/ AM & PM? The date should stay the same - the time is the only thing that needs formatting.
February 04, 2011 19:00:00
P.S. Using jQuery if that makes it any easier! Would also prefer a simple function/code and not use Date.js.
This is how you can change hours without if statement:
hours = ((hours + 11) % 12 + 1);
UPDATE 2: without seconds option
UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/
I created this function to do this:
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"));
//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;
For anyone reading who wants ONLY the time in the output, you can pass options to JavaScript's Date::toLocaleString() method. Example:
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 will be set to:
8:00 AM
Add "second: 'numeric'" to your options if you want seconds too. For all option see this.
Here's a reasonably terse way to do it using a Prototype:
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 ? "AM" : "PM";
var formattedTime = hours + ":" + minutes + " " + ampm;
return formattedTime;
}
Then all you have to do is convert your string value to a date and use the new method:
var stringValue = "February 04, 2011 19:00:00;
var dateValue = new Date(stringValue);
var formattedTime = dateValue.getFormattedTime();
Or in a single line:
var formattedTime = new Date("February 04, 2011 19:00:00").getFormattedTime();
Keep it simple and clean
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 doesn't have any Date utilities at all. If you don't use any additional libraries, the usual way is to create a JavaScript Date object and then extract the data from it and format it yourself.
For creating the Date object you can either make sure that your date string in the JSON is in a form that Date understands, which is IETF standard (which is basically RFC 822 section 5). So if you have the chance to change your JSON, that would be easiest. (EDIT: Your format may actually work the way it is.)
If you can't change your JSON, then you'll need to parse the string yourself and get day, mouth, year, hours, minutes and seconds as integers and create the Date object with that.
Once you have your Date object you'll need to extract the data you need and format it:
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".);
1) "Squared" instructions for making 24-hours became 12-hours:
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) In a single line (same result with slightly different algorythm):
var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");
Both options return string, like "5 pm" or "10 am" etc.
You can take a look at this. One of the examples says:
var d = new Date(dateString);
Once you have Date object you can fairly easy play with it. You can either call toLocaleDateString, toLocaleTimeString or you can test if getHours is bigger than 12 and then just calculate AM/PM time.
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
});
edit: I forgot to deal with 12 o'clock am/pm. Fixed.
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);
Here is the Demo
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;
}
Please try with below code
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(":");
}
Thanks
This worked for me!
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]);
}
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
I'm a relative newbie, but here's what I came up with for one of my own projects, and it seems to work. There may be simpler ways to do it.
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;
}
this is your html code where you are calling function to convert 24 hour time format to 12 hour with am/pm
<pre id="tests" onClick="tConvert('18:00:00')">
test on click 18:00:00
</pre>
<span id="rzlt"></span>
now in js code write this tConvert function as it is
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 ('');
}
converting 18:00:00 to 6:00:00PM working for me
This function will convert in both directions:
12 to 24 hour or 24 to 12 hour
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')
}
Here's some examples:
//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
Here you go
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 ;)
And here's the converter func for yas ;) Happy coding!!
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));
})();
This way you have more control over the output - i.e - if you wanted the time format to be '4:30 pm' instead of '04:30 P.M.' - you can convert to whatever format you decide you want - and change it later too. Instead of being constrained to some old method that does not allow any flexibility.
and you only need to convert the first 2 digits as the minute and seconds digits are the same in 24 hour time or 12 hour time.
var my_time_conversion_arr = {'01':"01", '02':"02", '03':"03", '04':"04", '05':"05", '06':"06", '07':"07", '08':"08", '09':"09", '10':"10", '11':"11", '12': "12", '13': "1", '14': "2", '15': "3", '16': "4", '17': "5", '18': "6", '19': "7", '20': "8", '21': "9", '22': "10", '23': "11", '00':"12"};
var AM_or_PM = "";
var twenty_four_hour_time = "16:30";
var twenty_four_hour_time_arr = twenty_four_hour_time.split(":");
var twenty_four_hour_time_first_two_digits = twenty_four_hour_time_arr[0];
var first_two_twelve_hour_digits_converted = my_time_conversion_arr[twenty_four_hour_time_first_two_digits];
var time_strng_to_nmbr = parseInt(twenty_four_hour_time_first_two_digits);
if(time_strng_to_nmbr >12){
//alert("GREATER THAN 12");
AM_or_PM = "pm";
}else{
AM_or_PM = "am";
}
var twelve_hour_time_conversion = first_two_twelve_hour_digits_converted+":"+twenty_four_hour_time_arr[1]+" "+AM_or_PM;

Categories