Store meridiem in a variable - javascript

I am using the following code:
var myDate= new Date();
myDate.toLocaleString( );
var x= myDate.getDay();
var y=myDate.gethours();
var z=myDate.getMinutes();
The time is in 12 hour format.
Now I need to store meridiem (AM or PM) in a variable. How can I do that?

How about this:
var y=myDate.getHours();
var meridiem = (y<12)?"AM":"PM";
alert(meridiem)

getHours() returns the hour in a 24 hour format. A quick solution would be:
var meridiem = (y >= 12) ? "PM" : "AM";

Wrapped into a nice tiny function!
function getMeridiem()
{
var d = new Date();
return (d.getHours() < 12) ? 'AM':'PM';
}

Related

How to remove dateT~~ in javascript?

I wrote code for getting the coming Saturday. So I wrote like this and the result is 2020-03-07T04:00:48.306Z. I found the dateT~~. I just only need the date. I can use the split method, but I don't wanna use this. is there any other way?
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff));
}
Try with substr,
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff)).toISOString.substr(0,10);
}
Your getSaturday function returns a new Date object (which is the Saturday).
The simplest way is to use split to get the date string back
const d = getSaturday(...)
d.toISOString().split("T")[0]
But since you don't want to use split. You may want to use moment: a very popular and lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
And then you can rewrite your function like this:
function getSaturday(d) {
return moment(d).day("Saturday").format("YYYY-MM-DD")
}
console.log(getSaturday(new Date()))
<script src="https://momentjs.com/downloads/moment.js"></script>
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff));
}
function dateSaturday(d) {
var ds = [
d.getFullYear(),
((d.getMonth()+1) < 10) ? `0${(d.getMonth()+1)}` : (d.getMonth() +1).toString(),
(d.getDate() < 10) ? `0${d.getDate()}` : d.getDate().toString()
];
return ds.join("-")
}
console.log(dateSaturday(getSaturday("2020-03-04")));
Date

I need to validate the format of time AM|PM

I have this code but its not working.How can i check if time is in AM or PM.
var time = $(id1).val();
var hrs = Number(time.match(/^(\d+)/)[1]);
var mnts = Number(time.match(/:(\d+)/)[1]);
var format = time.match(/\s(.*)$/);
//alert(format);
//alert(time);
if (format == "PM" && hrs < 12) {
hrs = hrs + 12;
}
if (format == "AM" && hrs == 12) hrs = hrs - 12;
You made a copy/paste mistake from my answer from three years ago (convert 12-hour hh:mm AM/PM to 24-hour hh:mm)
var format = time.match(/\s(.*)$/)[1];
Don't forget [1]

Comparing datetimes in javascript in format YYYY-MM-DD HH:MM:SS

I have to compare two date times in javascript. The dates I have are of the form
YYYY-MM-DD HH:MM:SS.
I am using the below code for it
var date1 = new Date("2015-08-20 09:38:20");
var date2 = new Date("2015-08-20 08:00:00");
The problem here is that when I use "/" in place of "-", I get the expected results. But when for this format I do
date1 > date
It returns false
Using momentJs is not an option for me and also I am getting the dates from soemewhere so would have to preserve the format. How do I compare the dates of the above given format in javascript
Try this:
var date1 = '2015-08-20 09:38:20';
var date2 = '2015-08-20 08:00:00';
var date1Updated = new Date(date1.replace(/-/g,'/'));
var date2Updated = new Date(date2.replace(/-/g,'/'));
console.log(date1Updated > date2Updated);
I was not able to reproduce the given behavior, but you could try
converting the date1 and date2 variables to miliseconds and storing those in separate vars since Jan 1st 1970.
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
this gives ( for your given example )
1440056300000
1440050400000
and in a comparison
date1_ms > date2_ms
returns true
This is typical of JavaScript dates. All browsers seem to treat date strings differently. My experience is write your own parser if you know the format you want to deal with.
Something like the below will work. Feel free to tidy it up and make it more generic for your own use.
function parseDateString(dateString) {
var dateParts = dateString.split(' ');
var dateOnlyString = dateParts[0];
var timeString = dateParts[1];
var dateOnlyParts = dateOnlyString.split('-');
var year = dateOnlyParts[0];
var month = dateOnlyParts[1] - 1;
var day = dateOnlyParts[2];
var timeParts = timeString.split(':');
var hours = timeParts[0];
var minutes = timeParts[1];
var seconds = timeParts[2];
return new Date(year, month, day, hours, minutes, seconds);
}
jsfiddle for test: http://jsfiddle.net/04nh4q9w/
function getDate(dateString) {
//This function assumes that the dateString will always be of the format YYYY-MM-DD HH:MM:SS
var dateParts = dateString.split(' ');
var dateStr = dateParts[0].split('-');
var timeStr = dateParts[1].split(':');
var dateTimeArr = datestr.concat(timestr)
return new Date(dateTimeArr[0], dateTimeArr[1]-1, dateTimeArr[2], dateTimeArr[3], dateTimeArr[4], dateTimeArr[5]);
}
var date1 = getDate("2015-08-20 09:38:20");
var date2 = getDate("2015-08-20 08:00:00");
date1 > date2 will be true for any browser.
function convertTo24Hour(time) {
time = time.toUpperCase();
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('AM') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('PM') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(AM|PM)/, '');
}

Converting isotime to shorttime in javascript

I have a ajax call which returns a time e.g 16:06:59 i want to convert it to 4:06 PM
var mydate = obj[0].time;
mydate comes 16:06:59 but when i try to use it with var date = new Date(), it gives me todays date .
Is there any solution to realize what i want ?
Thanks
The simplest answer is to split it into parts and then use them however you want, e.g.:
var parts = obj[0].time.split(":");
// parts[0] is now "16"
// parts[1] is now "06"
// parts[2] is now "59"
// Then perhaps (to get numbers and give the parts names)
var hours = parseInt(parts[0], 10);
var minutes = parseInt(parts[1], 10);
var seconds = parseInt(parts[2], 10);
...and of course for the first one you can use:
if (hours > 12) {
hours -= 12;
}
...if you want to do the a.m./p.m. thing. Just remember you did that and set your a.m./p.m. variable accordingly.
If you really want a Date instance, you can do this:
var dt = new Date();
dt.setHours(hours); // Be sure to use the real value here, not the one -12
dt.setMinutes(minutes);
dt.setSeconds(seconds);
try this :
function Convert24HoursTo12(time) {
var timeArray = time.split(':');
var hours = timeArray[0];
var minutes = timeArray[1];
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
and call it:
Convert24HoursTo12(obj[0].time);
See Demo Here.
You can do this:
"16:06:59".split(':').slice(0, 2)
.map(function (x, index) {
return index == 0 ? (x > 12 ? x - 12 + "PM" : x + "AM") : x
}).join(":").replace(/(.+?)((P|A)M)(.+)/, "$1$4 $2");
Modify the following code according to your need
var mydate= new Date();
var myhour=mydate.getHours();
var ampm="AM";
if(myhour==12)ampm="PM";
if(myhour==0)myhour=12;
if (myhour>12){
myhour-=12;
ampm="PM";
}else{
myhour=mydate.getHours();
}
var mytime=myhour+":"+mydate.getMinutes()+":"+mydate.getSeconds()+" "+ampm;
then use mytime variable anywhere you want
I have not checked it as I am in a hurry now. I hope it works well.

What is the best way of comparing the time component of a date object in javascript

I know this can be done by:
Comparing hour and minutes etc..
Comparing date.getTime() % 86400000
comparing date.toLocaleTimeString()
is there a straight forward way?
If you want to compare just the time component, you can do:
function isTimeEqual(d0, d1) {
return d0.getHours() == d1.getHours() &&
d0.getMinutes() == d1.getMintues() &&
d0.getSeconds() == d1.getSeconds() &&
d0.getMilliseconds() == d1.getMilliseconds();
}
You may not care about the milliseconds.
If you know that daylight saving is never observed at the location, or the times are UTC, you could do:
var msPerDay = 24*60*60*1000;
return d0 % msPerDay == d1 % msPerDay;
or
return !((d0 - d1) % 8.64e7);
I think the best method is the second one. But it can be done like this.
var d1 = new Date("10/10/2008 12:00");
var d2 = new Date("10/12/2008 12:30");
var diff = (d2-d1) % 86400000;
If you want it to work for d1 > d2,
var d1 = new Date("10/11/2010 12:00");
var d2 = new Date("10/10/2010 12:30");
d1.setFullYear(d2.getFullYear());
d1.setMonth(d2.getMonth());
d1.setDate(d2.getDate());
var diff = d2-d1;

Categories

Resources