Javascript .getHours() not working properly - javascript

Why am I not getting a zero, but an "18", from .getHours(), when comparing two dates that are separated by only seconds?
Here is the code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<span id="test">starting...</span>
<script>
var a = document.getElementById("test");
window.setInterval(myHourCheck, 1000);
var originalDate = new Date();
function myHourCheck() {
var current = new Date();
var original = originalDate;
var timeDelta = current.getTime() - original.getTime();
var hours = new Date(timeDelta).getHours();
a.innerHTML = hours;
}
</script>
</body>
</html>
Stepping through confirms that only seconds separate current from original.

new Date constructs a Date object with your local time zone. The hour offset is screwing you up.
You can get around this by using the UTC versions of the methods:
new Date(0).getUTCHours() === 0

Related

How to set a cache with Local Storage

I have a ads box and i want close it to by clicking x button so after it has been closed i don't want to se it until 24 hours with cache I created a localstorage but it's not working as i expected how should i edit my example
var showCase = Math.round(+new Date() / 1000);
document.getElementById("close_ads").addEventListener("click", function () {
if (typeof localStorage.showCase == 'undefined' || parseInt(localStorage.showCase) <= (showCase - 3600)) {
localStorage.showCase = showCase;
document.getElementById('reklam_box').style.display = 'none';
}
});
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
You need to use Localstorages .setItem() and .getItem check this out.
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
So something like this
// set the item
localStorage.setItem('showCase', 3600);
//get the item
var showCase = localStorage.getItem('showCase');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
<script>
var dontShowUntil = new Date(new Date().getTime() + 60 * 60 * 24 * 1000);
document.getElementById("close_ads").addEventListener("click", function () {
localStorage.dontShowUntil = dontShowUntil;
document.getElementById('ads_box').style.display = 'none';
});
if (new Date(localStorage.dontShowUntil) > new Date()) {
document.getElementById('ads_box').style.display = 'none';
}
</script>
</body>
</html>
useful linkes:
https://johnresig.com/blog/dom-storage/
https://developer.mozilla.org/en-US/docs/Web/API/Storage
NOTICE : when working with localStorage with array of objects you must save it like that:
Just convert the objects to JSON strings:
localStorage.setItem("savedData", JSON.stringify(objects));
var objects = JSON.parse(localStorage.getItem("savedData")));

How to parse date format, without access to source code

{$userinfo.create_account_date}
This returns me date in the following format: Oct-3-2017
I want to parse it to: DD/MM/YYY (03/10/2017)
The source code is encrypted. Is there a way to parse it through front-end only?
Front-end, assuming JavaScript. In most simple style.
function reformatDate(datumStr) {
var monthsArr = [];
monthsArr['Jan'] = '01';
// add missing months here
monthsArr['Oct'] = '10';
var dArr = datumStr.split('-');
return [dArr[1], monthsArr[dArr[0]], dArr[2]].join('/');
}
console.log(reformatDate('Oct-3-2017'));
Output:
3/10/2017
Addition to Karen's comment below.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function reformatDate(datumStr) {
var monthsArr = [];
monthsArr['Jan'] = '01';
// add missing months here
monthsArr['Oct'] = '10';
var dArr = datumStr.split('-');
return [dArr[1], monthsArr[dArr[0]], dArr[2]].join('/');
}
function elRfr(idName, datumStr) {
var id = document.getElementById(idName);
id.innerHTML = reformatDate(datumStr);
}
</script>
</head>
<body>
<div id="ourDate"><script type="text/javascript">elRfr('ourDate', 'Oct-3-2017');</script></div>
</body>
</html>
Karen, this is simplified example with just one DIV. In your case you should replace 'Oct-3-2017' with {$userinfo.create_account_date}, I guess.
If I assume correctly that your code is Salesforce Apex code.
Create a new var, initialize the date string as a new Date:
var d = new Date('Oct-3-2017');
Then manipulate it however you want with Date methods.

Passing data between two aspx pages using javascript

I need help with passing around data between two aspx pages (these aspx pages are stored in SharePoint Designer). I have created some JavaScript that does some simple calculations for metrics on our site.
https://tandemhospitalpartners.sharepoint.com/SitePages/Home.aspx
The following JavaScript is in the aspx link listed above.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
window.onload = function ()
{
}
function p1()
{
totalPts = 137;
setTotalPts(totalPts);
divId = document.getElementById('avg'); // element represents the ID 'countdown' for the div
today = new Date(); //this represents todays date in the following format
//Weekday ex. "Tue"
//Month ex. "Aug"
//Todays Date ex. "08"
//Year ex. "2017"
//Time ex. "13:44:54 GMT - 0500 (Central Daylight Time"
svOpen = new Date(2017, 06, 17); // this represents the first day we accepted patients
one_day = 1000 * 60 * 60 * 24;
//milliseconds
//minutes
//seconds
//hours
//We have been open for 23 days
daysOpen = Math.ceil((today.getTime() - svOpen.getTime()) / (one_day));
//subtracting SVNH open date from current date
avgPts = parseFloat(totalPts)/parseFloat(daysOpen);
divId.innerHTML ="Average Patients Per Day: "+ avgPts.toFixed(1);
}
function GetDays(element)
{
var el = document.getElementById(element);
today = new Date();
var cmas = new Date(today.getFullYear(), 6, 12);
if (today.getMonth() == 6 && today.getDate() > 13) {
cmas.setFullYear(cmas.getFullYear() + 1);
}
var one_day = 1000 * 60 * 60 * 24;
el.innerHTML =" Days to open the second Hospital: "+Math.ceil((cmas.getTime() - today.getTime()) / (one_day));
}
function setTotalPts(totalPts)
{
totId = document.getElementById("leOne");
totId.innerHTML = "This is my total patients: " + totalPts.toString();
}
</script>
</head>
<body onload="p1(); GetDays('count'); setTotalPts();"+"text"> <!-- this onload is passing the div ID to the function p1( element )
element represents the ID -->
<div id='count' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
<body>
<div id='avg' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
<body>
<div id='leOne' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
</html>
<!-- to keep a running count of the days i will have to subtract svOpen from todaysDate
My goal is to pass totalPts to an HTML ID that is on a different aspx file.
This is the link to the aspx file that contains the HTML ID I want to send it too.
https://tandemhospitalpartners.sharepoint.com/ININD/SitePages/Home.aspx
This is where I am really confused. I am not sure how to achieve this result. If anyone has ideas of how this could be done using JavaScript I would greatly appreciate it!
You cannot access another page's html from client side of another page as web is a stateless environment. But from the first page you can either pass the data through querystring to the next page or you can save data to localStorage, then navigate to the next page and retrieve data from localStorage. I prefer Querystring as it looks like its just a number you want to pass.
Suppose you have a button that opens up the second page
<asp:Button runat="server" ID="btnNext" OnClientClick="location.href='https://tandemhospitalpartners.sharepoint.com/ININD/SitePages/Home.aspx?totalPointes=' + getTotalPoints()" Text="Inind Home"></Button>
Then in the destination page the totalPoints from querystring and save it to the element. e.g.
$("#SomeID").val(getvaluefromQuerystring());
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#dvValue").html(getUrlParameter("totalPointes"));
});
//This function gets the querystring value from the querystring
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="dvValue"></div>
</div>
</form>
</body>
</html>

Can't get JavaScript output on website

The website is supposed to display a message counting down to the tax day. I can't seem to get anything to display on the page. The scrollbar doesn't even show up with the color even though I put in the write code. Some advice please.
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<title>TaxDay</title>
<script type="text/javascript">
<!-- Hide from old browsers
function scrollColor() {
styleObject=document.getElementsByTagName('html')[0].style
styleObject.scrollbarFaceColor="#857040"
styleObject.scrollbarTrackColor="#f4efe9"
}
function countDown() {
var today = new Date()
var day of week = today.toLocaleString()
dayLocate = dayofweek.indexOf(" ")
weekDay = dayofweek.substring(0, dayLocate)
newDay = dayofweek.substring(dayLocate)
dateLocate = newday.indexOf(",")
monthDate = newDay.substring(0, dateLocate+1)}
yearLocate = dayofweek.indexOf("2016")
year = dayofweek.substr(yearLocate, 4)
var taxDate = new Date ("April 16, 2017")
var daysToGo = taxDate.getTime()-today.getTime()
var daysToTaxDate = Math.ceil(daysToGo/(1000*60*60*24))
function taxmessage() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
taxDay.innerHTML = "<p style='font-size:12pt; font-
family:helvetica;'>Today is "+weekDay+" "+monthDate+" "+year+".
You have "+daysToTaxDate+" days to file your taxes.</p>"
}
}
//-->
</script>
The <div> id is taxDay if it's relevant. The body onLoad event handlers are scrollColor(); countDown(); and taxmessage().
you are not closing the countdown() function before the taxmessage() function - meaning that taxmessage is nested within countdown(). Also you do not have semicolons ";" after each line of the js. You should rewrite the code to either include the function of taxmessage() or close out countdown() first and call taxmessage with arguments passed to get the date variables.
check your console for errors

Javascript function checking dates

Hi I am new to Javascript and am trying to create a function that checks two dates. I have read it is useful to put the JS in the head part of the document, but this is not returning anything. I am also new to stackoverflow so I hope I did this correctly. :) Does anyone see the error?
<!DOCTYPE html>
<html>
<head>
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.write("<p>Just in time!</p>");
} else {
document.write("<p>Too late!</p>");
}
</head>
<body>
<br><br><br><br>http://www.epochconverter.com/
</body>
</html>
You have to mention it's a script using <script>. Also you shouldn't output DOM in the <head> like you are doing with document.write. Manipulate the DOM like this instead:
<head>
<script type="text/javascript">
var myDate = new Date(); // Your timezone!
var myEpoch = myDate.getTime()/1000;
var deadline = '1341596750.000';
document.write(myEpoch);
document.write("<br>",deadline);
if (myEpoch < deadline) {
document.getElementById("useme").innerHTML("Just in time!");
} else {
document.getElementById("useme").innerHTML("Too late!");
}
</script>
</head>
<body>
<p id="useme"></p>

Categories

Resources