Get Meridian from time in Javascript - javascript

I have following time "Mon Jun 22 03:45:24 PDT 2015" how can I get Meridian using Javascript.
I was doing this:
d= Mon Jun 22 03:45:24 PDT 2015;
var hours = d.getHours();
var meridiem = "AM";
if (d.getHours() > 12) {
hours = d.getHours() % 12;
if (hours == 2) {
hours = 12;
}
meridiem = "PM";
}
But its not working in IE 8.

you define
d= Mon Jun 22 03:45:24 PDT 2015;
actually it is nothing in javascript
some browser more intelligent some not, it's up to the browser behaviour
you have to tell javascript like that
function getCurrentTime() {
var currentTime;
// here we can give our date
var currentDate = new Date("Mon Jun 22 03:45:24 PDT 2015");
// OR we can define like that also for current date
// var currentDate = new Date();
var hour = currentDate.getHours();
var meridiem = hour >= 12 ? "PM" : "AM";
currentTime = ((hour + 11) % 12 + 1) + ":" + currentDate.getMinutes() + meridiem;
return currentTime;
}

We can get time in 12 hour format, including the meridian by using the Date.prototype.toLocaleTimeString() method with a US English argument which returns the time in AM/PM. Without the argument 'en-US' date will return the format it deems appropriate for your timezone.
From there we can utilise the slice method to get the last two characters of the timestamp using a negative index:
var d = new Date("Mon Jun 22 03:45:24 PDT 2015")
// US English uses 12-hour time with AM/PM
var timestamp = d.toLocaleTimeString('en-US');
// timestamp → "03:45:24 AM"
var meridian = timestamp.slice(-2);
// meridian → "AM"
One liner for brevity:
var meridian = new Date("Mon Jun 22 03:45:24 PDT 2015").toLocaleTimeString().slice(-2);

According to the documentation for JavaScript Date object here, there is no method for directly getting 12-hour hours and therefore no method for getting am/pm directly from the Date object.
You can get hours (24-hour format) which you can use to get 12-hour hours and am/pm. (You've already done it but I don't understand what you're trying to do in your code.)
This would be one way to do this.
This code is inspired by #tinka.
var d = new Date("Mon Jun 22 03:45:24 PDT 2015");
var h = (d.getHours() + 11) % 12 + 1; //Courtesy #tinka
var m = h > 12 ? 'pm' : 'am';
And you can always add methods to Date.prototype if you're gonna be using them repeatedly.
Date.prototype.getHours12 = function() {
return (this.getHours() + 11) % 12 + 1; // edited.
}
Date.prototype.getMeridiem = function() {
return this.getHours() > 12 ? 'pm' : 'am';
}
It should work on all platforms.

With Date object:
getMeridiem(date: Date) {
return date.toLocaleTimeString().split(' ')[1];
}

Related

How to set time with AM PM in Javascript Date Object

Say that I have DateTime in this format Fri Feb 02 2018 00:00:00 GMT+0530 (IST)
And from the time picker plugin getting the time 1:10am or 2:30pm in this format.
I am not sure how to calculate and combine/add them both to produce this result:
Fri Feb 02 2018 01:10:00 GMT+0530 (IST) or Fri Feb 02 2018 14:30:00 GMT+0530 (IST)
I wish if there was something to do as simple as this:
new Date(dateString).setHours(1:10am)
Seems like you need to parse it on your own:
function parseDaytime(time) {
let [hours, minutes] = time.substr(0, time.length -2).split(":").map(Number);
if (time.includes("pm") && hours !== 12) hours += 12;
return 1000/*ms*/ * 60/*s*/ * (hours * 60 + minutes);
}
To add it to a date:
new Date(
+new Date("Fri Feb 02 2018 00:00:00 GMT+0530")
+parseDaytime("1:20pm")
);
Here is a simple function to do what your after.
It basically splits the time using a regex, and then calls setHours & setMins, adding 12 hours if pm is selected.
The example below takes the current datetime, and sets 1:10am & 2:40pm..
function setHours(dt, h) {
var s = /(\d+):(\d+)(.+)/.exec(h);
dt.setHours(s[3] === "pm" ?
12 + parseInt(s[1], 10) :
parseInt(s[1], 10));
dt.setMinutes(parseInt(s[2],10));
}
var d = new Date();
console.log(d);
setHours(d, "1:10am");
console.log(d);
setHours(d, "2:40pm");
console.log(d);
You can parse the time string into hours & minutes, adjust the hours according to am/pm & set it to the date object then:
var dateString = 'Fri Feb 02 2018 00:00:00 GMT+0530 (IST)';
var hoursString = '2:30pm';
var parts = hoursString.replace(/am|pm/, '').split(':')
var hours = parseInt(parts[0]) + (hoursString.indexOf('pm') !== -1 ? 12 : 0);
var minutes = parts[1];
var date = new Date(dateString);
date.setUTCHours(hours, minutes);
console.log(date); // in your local time
console.log(date.toUTCString()); // in UTC (i.e. without timezone offset)
(Note setHours / setUTCHours mutates date object but returns unix timestamp of the updated datetime.)

Need just time from this date time format [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
I was looking for EDT time and got this in this format :
Wed Nov 01 2017 06:42:26 GMT+0530 (India Standard Time)
Although, I just want it like 6:42 AM to display !! I tried date time function
but doesnt help !!
Is it advisable to do this with any string function or will it give issue in future (I dont want any calculation on this )
Use moment.js format to work with date in JS.
moment("Wed Nov 01 2017 06:42:26 GMT+0530").format("hh:mm a")
You can use
var date = "Wed Nov 01 2017 06:42:26 GMT+0530";
var formattedDate = new Date(date);
var hours = formattedDate.getHours();
var minutes = formattedDate.getMinutes();
hours = (hours > 12) ? (hours - 12) : hours;
var period = (hours > 12) ? 'PM' : 'AM';
var time = hours + ':' + minutes + ' ' + period;
or you can also use moment.js, here is the details on 'format' function.
var time = moment(date).format("hh:mm A");
var date = new Date();
var hour = date.getHours();
var minutes = date.getMinutes();
var time = hour + ':' + minutes;
This would work.
Note: momentjs is great library for time manipulation, it is not good idea to include such a big library for small functions like this.

How can I convert a 8 digit number to date format

I have a 5 digit number stored in a variable. The next step is to convert the number to a date. for example
var x = 20151506;
The above number has to be converted to:
Thu June 15 2015 06:35:50
Please note that you must first specify the time in your original date value for it to be formatted and included correctly in your output. Thus the following will not provide the time element as you're looking for.
Referencing this SO answer:
function parse(str) {
var y = str.substr(0,4),
m = str.substr(6,2) - 1,
d = str.substr(4,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
Usage:
parse('20151506');
Output:
Mon Jun 15 2015 00:00:00 GMT-0500 (Central Daylight Time)
or in your case
parse(x.toString());
Output:
Mon Jun 15 2015 00:00:00 GMT-0500 (Central Daylight Time)
Code snippet provided below:
var x = 20151506;
function parse(str) {
var y = str.substr(0,4),
m = str.substr(6,2) - 1,
d = str.substr(4,2);
var D = new Date(y,m,d);
return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
//document.write (parse('20151506'));
document.write (parse(x.toString()));
To convert that "number" in to a Date you'll have to split it into the relevant year month day (hours, minutes and seconds appear to be missing).
var x = 20151506;
var month = x % 100;
var day = Math.floor(x % 10000 / 100);
var year = Math.floor(x / 10000);
var date = new Date(year, month - 1, day)
This will give you the value of date in whateve your local timezone is - Mon Jun 15 2015 00:00:00 GMT+0100 (GMT Daylight Time).
Not sure where you get the your time part from?

How to populate an input field with the time left before an event occurs using javascript and Date objects

So, I have a bug in my code somewhere. The "countdown" function needs to return a text string displaying the number of days, hours, minutes, and seconds between a starting date and a stopping date. The "changeYear" function needs to change a date's year value if the date has already been passed in the calendar year.
Something is amiss because, the text fields are not populating with the time left in days:hrs:min:sec for each event. Only thing that's showing up is the current date in the "thisDay" field. You can see this in my http://jsfiddle.net/gPjys/ jsfiddle where the "Countdown to Event" fields are blank.
Also, see the "HERE MAY BE WHERE THE PROBLEM LIES" in the following code:
function showCountdown(){
var today = new Date();
var Date1 = "Jan 14, 2011 at 10:00 a.m.";
var Date2 = "May 21, 2011 at 12:00 p.m.";
var Date3 = "Jul 4, 2011 at 9:00 p.m.";
var Date4 = "Sep 1, 2011 at 12:00 p.m.";
var Date5 = "Dec 1, 2011 at 11:30 a.m.";
var Date6 = "Dec 31, 2011 at 3:30 p.m.";
document.eventform.thisDay.value = showDateTime(today);
changeYear(today, Date1);
changeYear(today, Date2);
changeYear(today, Date3);
changeYear(today, Date4);
changeYear(today, Date5);
changeYear(today, Date6);
document.eventform.count1.value = countdown(today, Date1);
document.eventform.count2.value = countdown(today, Date2);
document.eventform.count3.value = countdown(today, Date3);
document.eventform.count4.value = countdown(today, Date4);
document.eventform.count5.value = countdown(today, Date5);
document.eventform.count6.value = countdown(today, Date6);
}
function showDateTime(time) {
date = time.getDate();
month = time.getMonth()+1;
year = time.getFullYear();
second = time.getSeconds();
minute = time.getMinutes();
hour = time.getHours();
ampm = (hour < 12) ? " a.m." : " p.m.";
hour = (hour > 12) ? hour - 12 : hour;
hour = (hour === 0) ? 12 : hour;
minute = minute < 10 ? "0"+minute : minute;
second = second < 10 ? "0"+second : second;
return month+"/"+date +"/"+year+" at "+hour+":"+minute+":"+second+ampm;
}
//HERE MAY BE WHERE THE PROBLEM LIES
function changeYear(today, holiday){
/*
insert a function named 'changeYear' that will
change a date's year value if the date has already been
passed in the current calendar year
*/
var year = today.getFullYear();
//The holiday parameter is used to store the date object representing one of the
//events in the event column of the form
holiday.setFullYear(year);
holiday = (holiday < today) ? year += 1 : year;
holiday.setFullYear(year);
}
function countdown(start, stop){
/*
will return a text string displaying the number of days,
hours, minutes, and seconds between a starting date and a
stopping date.
*/
var time = stop - start;
/*
convert the time difference into days, hours, minutes, seconds
and return the following text string
days days, hours hrs, minutes mins, seconds secs
*/
var days = time.getDate();
var hours = (days - Math.floor(days))*24;
var minutes = (hours - Math.floor(hours))*60;
var seconds = (minutes - Math.floor(minutes))*60;
return days + "days" + hours + "hrs" + minutes + "mins" + seconds + "secs";
}
http://jsfiddle.net/gPjys/
Thanks in advance! Cheers!
-QS
Interesting problem. The function must be:
function changeYear(today, holiday){
var todayYear = today.getFullYear();
holiday.setFullYear(todayYear);
if(today > holiday){
holiday.setFullYear(todayYear + 1);
}
}
And it works. But I also changed many other things, check here: http://jsfiddle.net/edgarinvillegas/gPjys/2/
Cheers, from La Paz, Bolivia

javascript date & time join

I have two date variable separately like following
startDate is a Date instance with the value Tue Jul 17 2012 00:00:00 GMT+0530 (IST)
startTime is a String with the value "11:30 AM"
Now what I need is join of both above date & time, as a Date.
startDateTime = Tue Jul 17 2012 11:30:00 GMT+0530 (IST)
I tried
new Date(startDate + " " + startDate) but outputting invalid date.
Also tried the way shown on this post. But still not working.
You can readily parse startTime if it's in a clearly-defined format, then use setHours and setMinutes: Live example | source
var startDateTime;
var parts = /^(\d+):(\d+) (AM|PM)$/.exec(startTime);
if (parts) {
hours = parseInt(parts[1], 10);
minutes = parseInt(parts[2], 10);
if (parts[3] === "PM" && hours !== 12) {
hours += 12;
}
else if (parts[3] === "AM" && hours === 12) {
hours = 0;
}
if (!isNaN(hours) && !isNaN(minutes)) {
startDateTime = new Date(startDate.getTime());
startDateTime.setHours(hours);
startDateTime.setMinutes(minutes);
}
}
...or something along those lines.
Note that key to this is the fact you've said startDate is a Date instance. The above assumes we're working within the timezone of the JavaScript environment, not across zones. If you were starting with a date string instead, and that string specified a timezone other than the JavaScript environment's timezone, which you were then converting into a Date via new Date("Tues Jul...."), then you'd have to be sure to adjust the resulting Date to use either the local time of the environment, or UTC; if you adjusted it to be UTC, you'd use setUTCHours and setUTCSeconds above instead of setHours and setSeconds. Again, this is only an issue if your starting point is a date string, and that string specifies a timezone different from the timezone in which the code above is running.
You can do This:
var theDate = new Date("Tue Jul 17 2012 00:00:00 GMT+0530 (IST)");
var theTime = "11:30 AM";
var hours = theTime .substr(0,2);
var minutes = theTime .substr(3,2);
var amOrPm = theTime .substr(6,2);
if (hours < 12 && "PM" == amOrPm) {
hours = +hours + 12;
}
theDate.setHours(hours);
theDate.setMinutes(minutes);
Try
new Date(startDate.toDateString() + " " + startTime)
This combines the date string from your Date object with the time string, and should give you a valid date. Note that this ignores the timezone you initially worked with, you might need to add " GMT+0530" again.
However, because your date string is already timezone-biased (Jul 16 2012, 20:30:00 UTC) it might be better to add them together, i.e. like new Date(+startDate + milliseconds):
var startDate = new Date("Tue Jul 17 2012 00:00:00 GMT+0530");
var startTime = "11:30 AM";
return new Date(+startDate + +new Date("1 1 1970 "+startTime))

Categories