How to get TimeZone wise local time using moment.js - javascript

i am working with two js library to get browser timezone id and browser local time
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>
<script src="Scripts/moment-timezone.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var tz = jstz.determine(); // Determines the time zone of the browser client
alert(tz.name());
alert(moment.tz(tz.name()).format());
});
</script>
this below code return perfect timezone id
var tz = jstz.determine(); // Determines the time zone of the browser client
alert(tz.name());
but this code is not working alert(moment.tz(tz.name()).format()); not giving user local time.
am i missing something in code? do i need to add any momentjs related other file ?
please guide me. i want to get user local time using moment.js. thanks
UPDATE Working Version
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/jstz.min.js"></script>
<script src="Scripts/moment.min.js" type="text/javascript"></script>
<script src="Scripts/moment-timezone-with-data-2010-2020.min.js" type="text/javascript"></script>
</head>
<body>
<form method="post" action="WebForm1.aspx" id="form1">
<div>
<script type="text/javascript">
$(document).ready(function () {
var tz = jstz.determine(); // Determines the time zone of the browser client
alert(tz.name());
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
alert(moment.tz('Europe/London').format(format));
alert(moment.tz(tz.name()).format(format));
});
</script>
</div>
</form>
</body>
</html>

My solution of this case (this is part of the page code):
function toLocalTime(time) {
if (time <= 0)
return '';
var m = moment.tz(time, 'America/Chicago'); //CDT
var tz = jstz.determine(); // Determines the time zone of the browser client
m.tz(tz.name()); // Convert CDT to local time
return m.format('HH:mm:ss');
}
<script src="js/jstz.min.js"></script>
<script src="js/moment.js"></script>
<script src="js/moment-timezone-with-data-2010-2020.js"></script>
...........
<script th:inline="javascript">document.write(toLocalTime(<<TIME IN MILLISECONDS HERE>>));</script>

Related

Replaced fixed variables in JS with inputs from HTML

I have downloaded some JavaScript code which creates a credit card paydown graph with and without overpayment. This code has fixed variables.
I would like to add HTML inputs for the user submit, however the script is connecting to a remote reference so I'm struggling to add a function to connect the script to HTML. Can HTML inputs be incorporated, if so, how?
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.3/clipboard.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.12.0/d3.min.js">
</script>
<script type="text/javascript" src="https://www.moneymage.net/mm.min.js"></script>
<div id="creditcard-interest-chart"></div>
<!--want to add input variables here-->
<script type="text/javascript">
//preventing me adding function below...
moneymage.ready(() => {
//fixed variables below...
var creditCardBalance = 5500;
var interestRate = 19.5 / 100.0;
var minimumMonthlyRepaymentPercent = 2.5 / 100.0;
var minimumMonthlyRepaymentFixed = 15.0;
var optionalMonthlyRepaymentOverAndAboveMinimum = 175;
var months = 25 * 12;
moneymage.createCreditCardInterestChart(creditCardBalance,
interestRate,
minimumMonthlyRepaymentPercent,
minimumMonthlyRepaymentFixed,
optionalMonthlyRepaymentOverAndAboveMinimum,
months,
"creditcard-interest-chart");
});
</script>
</body>
If you are waiting for user input you probably don't need to wait for moneymage to be ready, so you can just trigger the moneymage.createCreditCardInterestChart on a submit function for a form with the inputs you want.
This example would be the general idea to get you started: https://codesandbox.io/s/compassionate-night-sl156?file=/index.html

How to use JQuery and moment.js to automatically change date locale?

I want to change a fixed timestamp in English to German automatically with moment.js.
The timestamp looks like the following:
<time class="entry-timeago timestamp" datetime="2016-09-06">a month ago</time>
For this I have added the following code:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/locale/de.js"></script>
<script type="text/javascript">
var language = window.navigator.userLanguage || window.navigator.language;
moment.locale(language);
$('.timestamp').each(function (i, date) {
var $date = $(date);
$date.html(
moment($date.attr('datetime'))
.format('ll')
);
});
</script>
With this code I still cannot see a difference (even if I set moment.locale('de'); manually) and I wonder why.
Thanks for help.

How can I get timeStamp in my code

I want when page loaded get timeStamp but I can't.
This is my code :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id = "x">time</p>
<script src="jquery/jquery1.12.js"></script>
<script>
$(document).ready(function(event){
$("#x").text(event.timeStamp);
})
</script>
</body>
</html>
You can use Date object to do this work. now() method return timestamp in miliseconds. Of course javascript return timestamp with client time.
$(document).ready(function(event){
var timeStamp = Math.floor(Date.now() / 1000);
$("div").text(timeStamp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
You will not get event object in ready call. As a workaround you can use $.now() for instance:
$(document).ready(function(){
$("#x").text($.now());
});

Moving JavaScript from mark-up to separate .js file

My Javascript/html code looks like following which works great and shows country name in Part 1 below.
When i am trying to convert the code in .JS file it doesnt work means doesnt shows the country name in Part 2.. not sure what is wrong in the code
Part 1
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
</script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</body>
Part 2
// JavaScript Document
document.write("<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'></script>");
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
document.write("<script type='text/javascript' src='http://smart-ip.net/geoip-json?callback=GetUserInfo'></script>");
Here is the HTML of PArt 2
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude </title>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</table>
Include the jQuery reference as a real script tag in your HTML still - and remove the document.write.
Also ; on the end of your var list... Perhaps.
Your <head> tag should be
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude
</title>
<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'>
</script>
<script src="test.js" type="text/javascript"></script>
</head>
As Paul notes document.write is deprecated. You should always try to include <script> tags rather than manipulating the DOM. I think that the way you were doing it would mean that the jQuery code in your file would be executing before jQuery had loaded - due to the fact that you are writing the tag directly to the DOM immediately before your code. So there will not have been time to parse it. I would think that this code would have raised an error in fact.

Countdown Timer that doesn't reset when you refresh the page?

I Need to have a code for the timer that doesn't reset the countdown timer even you refresh the page.
I saw sample code at keith wood plug in, but don't know how to implement this in my html file.
here's the link :
http://keith-wood.name/countdown.html
I hope somebody could help me! thanks! :)
I just need Hour, Minutes and Seconds to show. And after the Time given, there is a prompt box that will show "Time is up! " . This one is for the online exam we are developing. Thank you so Much! :)
If you know that the user will have local cache enabled and able to store data, you could save 2 values to localStorage, 1 for the currentTime and 1 for the targetTime. Then you compare the 2 in an interval and if currentTime > targetTime, display your message.
Also bind to the onbeforeunload event and save the new currentTime back into localStorage. This will give you the persisted countdown you are seeking.
Here is an example of how you can do this:
var interval;
let minutes = 1;
let currentTime = localStorage.getItem('currentTime');
let targetTime = localStorage.getItem('targetTime');
if (targetTime == null && currentTime == null) {
currentTime = new Date();
targetTime = new Date(currentTime.getTime() + (minutes * 60000));
localStorage.setItem('currentTime', currentTime);
localStorage.setItem('targetTime', targetTime);
}
else{
currentTime = new Date(currentTime);
targetTime = new Date(targetTime);
}
if(!checkComplete()){
interval = setInterval(checkComplete, 1000);
}
function checkComplete() {
if (currentTime > targetTime) {
clearInterval(interval);
alert("Time is up");
} else {
currentTime = new Date();
document.write(
"\n <font color=\"white\"> Seconds Remaining:" + ((targetTime - currentTime) / 1000) + "</font>");
}
}
document.onbeforeunload = function(){
localStorage.setItem('currentTime', currentTime);
}
Note that I would've made a snippet however stackoverflow and other online IDE's are complaining about security breaches. Note that this is perfectly valid and does not breach any security. Save it as a .js and run.
To start the "countdown" again, invoke localStorage.clear().
Include the jQuery library in the head section of your page.
Download and include the jQuery Countdown CSS and JavaScript in the head section of your page.
Alternately, you can use the minimised version jquery.countdown.min.js (13.5K vs 31.4K, 4.4K when zipped).
Connect the countdown functionality to your divs.
So, your final code will be:
<html>
<head>
<title>jQuery Countdown</title>
<style type="text/css">#import "jquery.countdown.css";</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.countdown.js"></script>
<script type="text/javascript">
$(function () {
var year = new Date();
year = new Date(year.getFullYear(), 11 - 1, 20);
$('#dvCountDown').countdown({until: year, format: 'HMS'});
$('#year').text(austDay.getFullYear());
});
</script>
</head>
<body>
<h1>jQuery Countdown Basics</h1>
<p>Counting down to 20 November <span id="year">2012</span>.</p>
<div id="dvCountDown"></div>
</body>
</html>
Hope this helps!
If you want to use that script then you'll have to count by date and not a custom countdown value in order for it not to get reset on page refresh: http://jsfiddle.net/qWERa/1/
//Custom countdown value starting on page load
$('#CountdownbyValue').countdown({until: '+0h +0m +8s', format: 'HMS',onExpiry: liftOff,});
//Countdown by Date
$('#CountdownbyDate').countdown({until: new Date(2012, 11-1, 17, 10, 10, 10), format: 'HMS',onExpiry: liftOff,});
//Time is up dialog!
function liftOff() {
alert('Time is up!');
}
Full Code:
<html>
<head>
<title>Demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<script type='text/javascript' src='http://keith-wood.name/js/jquery.countdown.js'></script>
<link rel="stylesheet" type="text/css" href="http://keith-wood.name/css/jquery.countdown.css">
<script type='text/javascript'>
$(window).load(function(){
//Starts from time of page load
$('#CountdownbyValue').countdown({until: '+0h +0m +8s', format: 'HMS',onExpiry: liftOff,});
//Counts by Date
$('#CountdownbyDate').countdown({until: new Date(2012, 11-1, 17, 10, 10, 10), format: 'HMS',onExpiry: liftOff,});
//Time is up!
function liftOff() {
alert('Time is up!');
}
});
</script>
</head>
<body>
<div id="CountdownbyValue"></div>
<div id="CountdownbyDate"></div>
</body>
</html>
Your can also try:
window.onbeforeunload = function() {
return "Are you sure you want to quit this exam?";
}
I suggest you take a look at this Countdown timer with cookies

Categories

Resources