Compare hardcoded date with the current date - javascript

I am trying to compare dates in javascript.
I have a hardcoded date (03/23/2015 11:20 am) in of , and I am trying to compare it with the current date in the same format.
But I am always getting it as not same.
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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 date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var timeNow = formatDate(D);
var startTime6 = document.getElementById('tno6_time').innerHTML;
if (timenow == startTime6) {
alert("Same");
}
else {
alert("not same");
}

Your's javascript portion :
var d = new Date();
var timeNow = formatDate(D);
if (timenow == startTime6) {
alert("Same");
}
Here check in above code you are creating variable with name d and you are passing variable D which is not declared.Here you have also typo in timeNow not timenow.It should be like
var timeNow = formatDate(d);
if (timeNow == startTime6) {
alert("Same");
}
Apart from that check both the variables value either with console.log() function or with alert() and see if there are same then It should alert the 'Same' else 'not same'.
And keep in mind new Date() will always give you current time so if you are comparing with hard coded date then Only once there are the possibility that result should come 'Same' and It will only occur when you are executing this code when the hard coded date and time exactly the same.
It is very hard to check your code in that way because millisecond change will affect your result.
Check this demo

Related

I nee to add "0" before minutes <10 in Typescript

I need to display the time and the minutes are not working correctly. It is returning 12:4, 2:3..when the minutes are less than 10 there is not 0. I tried adding the "0" like this:
var formattedTime = new Date(time + 'z');
var hours = formattedTime.getHours();
var amOrPm = hours >= 12 ? 'PM' : 'AM';
hours = (hours % 12) || 12;
var minutes = formattedTime.getMinutes();
if (minutes < 10) {
("0" + minutes)
};
var finalTime = eventDate +" "+ hours + ":" + minutes + " " + amOrPm;
Any help is welcome(I am new to coding). Thank You.
The statement ("0" + minutes) doesn't do anything. It does add a '0' to minutes, but you're not doing anything with the result. The problem is that you need to set the result of this statement in a new variable.
But here's an easier way to do this:
const minutes = 5;
const minuteStr = minutes.toString().padStart(2, '0');

Page last modified using Javascript with 12 hour clock showing am or pm

I'm trying to create a script in Javascript that shows when a page was last modified, which returns the date, time, in am or pm format, of modification.
Clearly I am doing something wrong. I can't get the script to run, and it will be in my function AmPm. Can someone please help?
// Javascript code for page modification
// Shows the date, time, am or pm, of modification.
// This section sets the date of modification
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "." + (modiDate.getMonth() + 1) + "." + modiDate.getFullYear();
return showAs
}
// This section sets the time of modification
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
// This section writes the above in the document
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
// This section decides if its am or pm
function AmPm() {
var hours = new Date().getHours();
var hours = (hours + 24 - 2) % 24;
var mid = 'AM';
if (hours == 0) { // At 00 hours (midnight) we need to display 12 am
hours = 12;
} else if (hours > 12) // At 12pm (Midday) we need to display 12 pm
{
hours = hours % 12;
mid = 'PM';
}
}
var mid = //This is where I am stuck!!
return AmPm
document.write("This webpage was last edited on: ");
document.write(lastModified() + " at " + GetTime() + AmPm());
document.write("");
document.write(" NZ Daylight Savings Time.");
document.write("");
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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;
}

Date formating gives different results in Chrome than in other browsers?

I want to show the time in a readable format. So I am using the below js code. But the output is different in Chrome and IE. How do I change the code to give the same output across all the browsers ?
The output in IE : 12:46 am
In Chrome : 6:16 am
Time zone is : UTC +05:30
var unReadableDate = "2016-01-25T00:46:00";
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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;
}
Can you please try replacing this
var unReadableDate = "2012-06-25T00:46:00.000Z"
var newDate = new Date(unReadableDate);
//var timeZoneOffset = (new Date()).getTimezoneOffset();
//newDate.setMinutes(newDate.getMinutes() - timeZoneOffset);
alert(formatAMPM(newDate));
//below function formats time in am and pm
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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;
}
Converting a UTC format string to a date using Javascript Date constructor is not reliable. If you want to tackle timezone issues with date you should use moment.js. To understand more you can use below link.
Javascript Date issue
OR simple way to resolve the issue is pass individual arguments in the date instead of complete string. To understand more you can use below link
DateTime UTC
Your problem is that your date string being treated as a local time vs it being treated as UTC.
Just make it unambiguous by specifying the time zone. Change
var unReadableDate = "2016-01-25T00:46:00";
to
var unReadableDate = "2016-01-25T00:46:00Z";

Format a time string with zero based hours and minutes in javascript

This is what have tried:
partly pseudocode:
var hours = date1.getHours();
var minutes = date2.getMinutes();
if (hours.length == 1)
hours = "0" + hours;
if (minutes.length == 1)
minutes = "0" + minutes;
var time = hours + ':' + minutes;
Is there a smarter way like a formatted string function where I can say:
var minutes = date.getMinutes('mm');
var hours = date.getHours('hh');
so it adds the zeros automatically ?
Here is your code fixed since there is no length on an integer
var hours = date1.getHours();
var minutes = date2.getMinutes();
if (hours<10) hours = "0" + hours;
if (minutes<10) minutes = "0" + minutes;
var time = ""+ hours + ":" + minutes;
You do not need a framework and there is no shorter way to do this
This may be what you mean:
Live demo
function pad(num) {
return ("0"+num).slice(-2)
}
var time = pad(date1.getHours())+":"+pad(date2.getMinutes());
This functionality doesn't exist natively in javascript, you have to either add it yourself (as you have started to do), or, use a package.
moment
Mozilla has an example
Here's a blog post to a date formatting function
Where can I find documentation on formatting a date in JavaScript?
How to format a JavaScript date
Use DateJS and you will be able to use mm and hh to add the preceding zeros :)
https://code.google.com/p/datejs/wiki/FormatSpecifiers
You can add a method to Number prototype
Number.prototype.pad0 = function(length) {
var result = this.toString();
while(result.length<length) result = "0"+result;
return result;
}
Then you can get what you want
var date = new Date();
console.log(date.getMinutes().pad0(2));
console.log(date.getHours().pad0(2));
Yet another way of doing it:
var d = new Date();
var t = [ d.getHours(), d.getMinutes(), d.getSeconds() ];
var s = t.map( function(z){return ('00'+z).slice(-2)} ).join(':');
console.log(s);
Time parts are put into an array. That array goes through map() where the numbers get leading zeros. The resulting array is then joined into a string with the ":" separator.
Convert numbers to strings before you check the lengths:
var hours = String(date1.getHours());
var minutes = String(date2.getMinutes());
if (hours.length == 1)
hours = "0" + hours;
if (minutes.length == 1)
minutes = "0" + minutes;
var time = hours + ':' + minutes;

display time am/pm inside a div with javascript

Hi Everyone I am sorry if this question has been answered before but I haven't been able to find a solution. I am completely new to js so please be nice :)
I wanted to ask how can I have the time display inside a div? I can't get this function to display on my page. When I launch the page in the browser, it is just blank.
Thank you, I hope my question makes sense.
document.getElementById("para1").innerHTML = formatAMPM(date);
function formatAMPM(date) {
var elem = document.getElementById("para1");
var hours = date.getHours();
var minutes = date.getMinutes();
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;
}
You need this:
document.getElementById("para1").innerHTML = formatAMPM(new Date());
And you might also want to wrap it in something like jQuery's ready() to make sure the DOM has been loaded:
$(document).ready(function() {
// Handler for .ready() called.
});
http://api.jquery.com/ready/
jQuery's isn't the only way, but just a suggestion.
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours || 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
DEMO VIEW
You can return it in a user-familiar time string with toLocaleTimeString().
A replace will remove the seconds counter-
function formatAMPM() {
var d=new Date().toLocaleTimeString();
return d.replace(/^(\d{2}:\d{2}):\d{2}(.*)/, '$1$2');
}
Or you can call this or your method on a timer-
onload= function(){
window.showTimer= setInterval(function(){
var date= new Date(),
hours= date.getHours(),
time= date.getMinutes();
if(time<10) time= '0'+time;
document.getElementById("para1").innerHTML=
(hours%12 || 12)+':'+time+(hours>= 12? ' pm':' am');
},1000);
}

Categories

Resources