Is there a way to directly format the time in Javascript? - javascript

What I want it is to get the output of the current time with Javascript. The output should be something similar as:
15:28:30 PM
And I got this using the following code:
var date = new Date();
document.write("Current time: " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
if (date.getHours() <= 12)
document.write(" AM");
else
document.write(" PM");
So the output that I get it is:
Current time: 3:0:16 AM
But I want to know if there is some faster or cleaner solution to solve this problem because I think my solution it is not good at all.
Is it possible to get the same behaviour with a better method or solution?
Thanks in advance!

var date = new Date();
var time = date.toLocaleString('en').split(', ').pop();
This will give you the exact format you are looking for. Although I would go with a library like Moment.js or Date.js. Tons of options with those.

It's like this:
var dt = new Date;
console.log(dt.toLocaleTimeString());

I see nothing wrong with your approach. However, if you want the flexibility of different formats, there's a library called moment.js which allows you to build and format dates.
moment().format('hh:mm:ss A'); // 12:00:00 AM

I think that you make right way. Only need modify a little to get your expectation:
var date = new Date();
int hour = date.getHours();
string abbr;
if (date.getHours() <= 12)
abbr = " AM";
else {
hour = hour + 12;
abbr = " PM";
}
document.write("Current time: " + hour + ":" + date.getMinutes() + ":" + date.getSeconds() + abbr);

var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
Found this thread

Related

Extract time from JS Date object without offsetting the Time zone

So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:
"2017-12-29T20:00:00"
What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:
"M/d/yyyy"
"hh:mm AM/PM" (12 hour)
I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.
Consider just reformatting the string, it avoids all issues with the built-in parser and timezones:
function reformatTimestamp(s) {
function z(n){return (n<10?'0':'')+ +n}
var b = s.split(/\D/);
var h = b[3]%12 || 12;
var ap = b[3] < 12? 'AM':'PM';
return b[1] + '/' + b[2] + '/' + b[0] +
' ' + z(h) + ':' + z(b[4]) + ' ' + ap;
}
console.log(reformatTimestamp('2017-12-29T20:00:00')) // 12/29/2017 08:00 PM
I think it would be better to pad the month and day with a leading zero (but I'd also use an unambiguous date format like DD-MMM-YYYY rather than the peculiar m/d/y).
Use this code:
function formatAMPM(date) {
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var str = "2017-12-29T20:00:00";
var dt = new Date(str + "Z");
console.log("M/d/yyyy");
console.log((dt.getUTCMonth() + 1) + '/' + dt.getUTCDate() + '/' + dt.getUTCFullYear());
console.log("hh:mm AM/PM");
console.log(formatAMPM(dt));

Date format conversion in node js

I am using a form ,from which the user can select the datetime from datetime picker in dd-mm-yyyy hh:mm:ss format. Now I want to convert the format to yyyy-mm-dd hh:mm:ss format to store in mysql table.
I tried with moment js like this
console.log(moment(status.date).format('MM/DD/YYYY'));
where status.date I will post from a form where the user selects datetime from datetimepicker.
Please help
You can do like this instead of having some modules.
var fd = status.date;
var fromDate = fd.split(" ");
console.log(formatDate(fromDate[0],fromDate[1] + " " + fromDate[2]));//
and add these functions there.
function formatDate(date, time2) {
var from = date.split("-");
var f = from[2] + "-" + from[1] + "-" + from[0];
var time1 = time(time2);
return f + " " + time1;
}
function time(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if ((AMPM == "PM" || AMPM == "pm") && hours < 12)
hours = hours + 12;
if ((AMPM == "AM" || AMPM == "am") && hours == 12)
hours = hours - 12;
var sHours = hours.toString();
if (hours < 10)
sHours = "0" + sHours;
if (minutes < 10)
sMinutes = "0" + sMinutes;
return (sHours + ":" + sMinutes);
}
Convert it to ISOString first and then eliminate unwanted things by replace method.
var date = new Date();
date.toISOString().replace(/T/, " ").replace(/\..+/,'')
source: chbrown's answer
Building on top of Prateek Jain's ISOString method, we can use toLocaleString to obtain the local time in ISO format.
One needs to shop around the base format provided by toLocaleString according to different regions. The format closest to ISO is en-CA (refer to this answer for all the region-based format). We then use the option {hour12: false} to convert to 24-hour notation.
const d = new Date();
d.toLocaleString('en-CA', {hour12: false}).replace(/, /, ' ');

Javascript: Adding digits without Sum?

I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()

JavaScript AM/PM time comparison

Suppose I have 2 datetime variables:
var fromdt = "2013/05/29 12:30 PM";
var todt = "2013/05/29 01:30 AM";
I want to compare these 2 datetimes. How can I get Javascript to recognize whether the time is AM or PM?
I think Javascript will compare the time in 24 hours format. Do I need to convert the time to 24 hour format? Is that correct? Could someone please suggest the correct solution....
Just use straight javascript functions
var fromdt = "2013/05/29 12:30 PM";
var todt = "2013/05/29 01:30 AM";
var from = new Date(Date.parse(fromdt));
var to = new Date(Date.parse(todt));
alert(from);
alert(to)
if (from > to) alert("From");
else alert("To");
Once the date is parsed into date form, you can do what you like with it. And you can compare dates using the standard operator signs ( >, < etc)
I'm not sure what you need to do with them, but http://www.w3schools.com/jsref/jsref_obj_date.asp is an okay reference.
And heres a crappy sandbox with the above code http://jsfiddle.net/QpFcW/
and a better one that XX deleted :( http://jsfiddle.net/QpFcW/1/
Use this function
function get_time() {
var time_t = "";
var d = new Date();
var cur_hour = d.getHours();
cur_hour < 12 ? (time_t = "am") : (time_t = "pm");
cur_hour == 0 ? (cur_hour = 12) : (cur_hour = cur_hour);
cur_hour > 12 ? (cur_hour = cur_hour - 12) : (cur_hour = cur_hour);
var curr_min = d.getMinutes().toString();
var curr_sec = d.getSeconds().toString();
if (curr_min.length == 1) {
curr_min = "0" + curr_min;
}
if (curr_sec.length == 1) {
curr_sec = "0" + curr_sec;
}
$("#updatedTime").html(
cur_hour + ":" + curr_min + ":" + curr_sec + " " + time_t
);
alert(cur_hour + ":" + curr_min + ":" + curr_sec + " " + time_t);
}

Chrome Javascript Date AM | PM

I would like to get this format:
2:18:00 pm
Using the sample code from w3Schools.com below, I can get the correct results from IE and FireFox. But when it comes to Chrome, I get the 24hr clock version where it is simply displayed this way:
14:18:00
In FF
new Date().toLocaleTimeString()
// 2:18:00 pm
function twoDigitPad(number) {
return ("0" + number).slice(-2);
}
function twelveHourTimeString() {
var date = new Date();
var hour = date.getHours();
var min = twoDigitPad(date.getMinutes());
var sec = twoDigitPad(date.getSeconds());
var ampm = hour < 12 ? "am" : "pm";
hour = hour % 12 || 12; // convert to 12-hour format
return hour + ":" + min + ":" + sec + " " + ampm;
}
date.getHours() returns an integer between 0 and 23, which hour % 12 || 12 converts to the 12-hour format.
date.getMinutes() and date.getSeconds() each return an integer, so you'll need to zero-pad those values when they're less than 10. Optionally, hour as well.
Use the following javascript code,
<script type="text/javascript">
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if (curr_hour < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
document.write(curr_hour + ":" + curr_min + ":"
+ curr_sec+ a_p);
</script>
The o/p would be as you expect,2:18:00 PM
Dealing with dates reliably cross-browser is a ball-ache in javascript- I would use the DateFormat library; http://blog.stevenlevithan.com/archives/date-time-format
then as he notes on the page, you can call it like so;
dateFormat(now, "h:MM:ss TT");
There are a few alternatives, but this one seems the most light-weight.

Categories