Format Moment.js Duration - javascript

I am using Moment.js to track the duration of an action in my app. Currently, I have the following code:
var startMoment = null;
var actionClock = null;
function startClock() {
actionClock = setInterval(function(){
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
startMoment = null;
actionClock = null;
}
My problem is, the format of duration is awkward. I want to display the duration as mm:ss.lll. In other words, always show two digits for the minutes, two digits for the seconds, and three digits for the milliseconds. Currently, I see durations printed like 1:2.45. How do I format a duration created with Moment.js? If this is not possible, is there another library I should be using to track a duration and display it?
Thank you!

One way of doing this might be to convert your duration back into a moment (perhaps using milliseconds), and then using the moment's formatting.
moment.utc(span.asMilliseconds()).format('mm:ss.SSS');
var startMoment = null,
$durForm = $('#durationFormatted');
var actionClock = null;
function startClock() {
actionClock = setInterval(function() {
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
$durForm.text('00:00.000');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
startMoment = null;
actionClock = null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<div>Duration (original): <span id='duration'></span>
</div>
<div>Formatted moment: <span id='durationFormatted'></span>
</div>
<button onClick='startClock()'>Start Clock</button>
<button onClick='stopClock()'>Stop Clock</button>

I had a similar issue in my project and thankfully, Lodash was already a dependency. I was able to use the _.padStart method to get there.
let yourHours = _.padStart(span.hours().toString(),2,'0');
let yourMinute = _.padStart(span.minutes().toString(),2,'0');
let yourSeconds = _.padStart(span.seconds().toString(),2,'0');

Related

Show hourly weather from API using DOM

I am trying to show the hourly weather on my website from this API: https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/18.1489/lat/57.3081/data.json
I have a hard time understanding the functions needed to do so. I think I need some sort of loop, but can't figure out what to put in it. This is my code so far:
export async function getWeather() {
var res = await fetch("https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/18.1489/lat/57.3081/data.json");
if (res.ok)
return await res.json();
else
alert('HTTP Error: ' + res.status);
}
--My other file--
import {getWeather} from './fetch.js'
async function generate_weather() {
var jsonRes = await getWeather();
var i = 0;
if(jsonRes.timeSeries[i].validTime == timeNow())
{
document.createTextNode(jsonRes.timeSeries[i].parameters[i].values[0] + " grader");
}
}
function timeNow() {
var date = new Date();
var hours = date.getHours();
return hours;
}
generate_weather();
I tried the example below, but it didn't work. Am I missing a step?
async function generate_weather() {
var jsonRes = await getWeather();
for (let times in jsonRes.timeSeries) {
let currentTime = times.validTime;
let date = new Date(currentTime);
let currentHour = date.getHours();
for (let param in times.parameters) {
let value = param.values[0];
let unit = param.unit;
}
for (var i = 0; i == currentHour;) {
var newElement = document.createElement('h2');
var newElementText = document.createTextNode(jsonRes.timeSeries[i].times[i].parameters[0]);
newElement.appendChild(newElementText);
document.getElementById("body").appendChild(newElement);
}
}
}
generate_weather();
In response, you have two arrays one for timeseries and other for parameters inside the timeseries-
So, you will have to use loop inside the loop like this in generate_weather function -
for (let times in jsonRes.timeSeries) {
let currentTime = times.validTime;
let date = new Date(currentTime);
let currentHour = date.getHours();
for (let param in times.parameters) {
let name = param.name;
let value = param.values[0];
let unit = param.unit;
Console.log('Tempreture of ' + name + ' is ' + value + ' ' + unit); // Tempreture of t is 14.8 Cel
}
}
Above code will show the tempreture of every name per every hour, if you need to show the tempreture for any specific name then you can use if/else statement.

Show clock/time increment from javascript

I tried to show/increment the only time(Hours, Minutes and Seconds) like a timer from getting server side, but it's not working for me.
For this I tried below code.
Can you please help me to run the specified time (Server Time) to run as Timer.
What I have tried:
c#
ScriptManager.RegisterStartupScript(Page, this.GetType(), "close", "OnRunnTimer("+0.21023+");", true);
// JS COde
//Server time I am sending serverTimeP = 0.21023
function OnRunnTimer(timeP) {
setInterval(function () { runJSTimer(timeP); }, 1000);
}
function runJSTimer(serverTimeP) {
var d = new Date();
d.setHours(serverTimeP);
var hours = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
lblJsTimer.SetText(hours + ":" + min + ":" + sec);
}
Can you please help on this.
I'm not sure if I understood, but this is my example of solution to what I think to be your issue.
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var hours = 0;
var min = 0;
var sec = 0;
var serverTime = '2021-02-17T14:34:14.426Z'; // server time example in ISO format
var refreshTimeLabel = function(){
document.getElementById("timeLabel").innerHTML = hours + ":" + min + ":" + sec;
}
var refreshVariables = function () {
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTime = updatedServerTimeDate.toISOString();
hours = updatedServerTimeDate.getHours();
min = updatedServerTimeDate.getMinutes();
sec = updatedServerTimeDate.getSeconds();
}
var startTimer = function() {
setInterval(function () {
refreshVariables();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>
Variant for multiple rows
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var serverTimes = ['2021-02-17T16:34:45.426Z', '2021-02-17T14:54:14.426Z', '2021-02-17T14:00:00.426Z']; // server time array example in ISO format
var refreshServerTimeByIndex = function (index) {
var serverTime = serverTimes[index];
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTimes[index] = updatedServerTimeDate.toISOString();
}
var refreshServerTimes = function(){
var i;
for(i = 0; i < serverTimes.length; i++){
refreshServerTimeByIndex(i);
}
}
var getTimeTextByDateISO = function(dataISO){
var date = new Date(dataISO);
var hours = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
return hours + ":" + min + ":" + sec;
}
var refreshTimeLabel = function(){
var textLabel = "";
var i;
for(i = 0; i < serverTimes.length; i++){
textLabel += " | " + getTimeTextByDateISO(serverTimes[i]);
}
document.getElementById("timeLabel").innerHTML = textLabel;
}
var startTimer = function() {
setInterval(function () {
refreshServerTimes();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>

Problems calculating time difference Moment.js

function myFunction() {
moment.locale('pt-BR');
var intervalo = moment();
var periodo = moment("2000", "hmm").format('LT');
var atual = moment().format('LT');
document.getElementById("atual").innerHTML = "Atual: " + atual;
document.getElementById("periodo").innerHTML = "Periodo:" + periodo;
intervalo=periodo.diff(atual).format('LT');
}
In the browser, it displays the message: periodo.diff is not a function
at myFunction.
I want to calculate the difference between the current time at a specified time, timing the remaining time
The format method turns the moment object into a string. Try this:
function myFunction(){
moment.locale('pt-BR');
var periodo = moment("2000", "hmm");
var atual = moment();
var intervalo=periodo.diff(atual, 'years', true);
document.getElementById("atual").innerHTML = "Atual: "+atual.format('LT');
document.getElementById("periodo").innerHTML = "Periodo:"+periodo.format('LT');
document.getElementById("intervalo").innerHTML = "Intervalo:"+intervalo;

new Date return NaN or a wrong time starting from server date()

I'm trying to get server time at start and update it, cause i've to cotnrol some elements with real time. The problem is that if my serverTime doesn't have T the time is NaN on firefox and IE, but if i replace the empty space with T on chrome and IE i've a wrong time.
I now the work-around of replacing white space with T sucks but im outta of time :)
Thanks everybody
At start:
$tmpTime = date("Y-m-d H:i:s");
Head:
<script>
var serverTime = '<?=$tmpTime?>';
serverTime = serverTime.replace(" ", "T");
</script>
Script:
setInterval(function () {
console.log(serverTime);
var tmpTime = new Date(serverTime);
console.log(tmpTime);
var t = tmpTime.getTime();
t = t + 1000;
tmpTime = new Date(t);
serverTime = t;
if (tmpTime.getMinutes() < 10) {
var minutes = "0" + tmpTime.getMinutes();
} else {
var minutes = tmpTime.getMinutes();
};
newTime = tmpTime.getHours() + ":" + minutes;
$('#liveTime').text(newTime);
if ($("#program li[time-id='" + newTime + "'][class='alert']").length !== 0) {
alert("Lo streaming da te programmato sta per iniziare!");
$("#program li[time-id='" + newTime + "'][class='alert']").removeClass("alert");
}
titleToShow();
}, 1000);
function titleToShow() {
$("#program li").each(function () {
var prevTime = $(this).prev("li").attr("time-id");
var thisTime = $(this).attr("time-id");
var nextTime = $(this).next("li").attr("time-id");
currentTime = Date.parse('01/01/2011 ' + newTime);
prevTime = Date.parse('01/01/2011 ' + prevTime);
nextTime = Date.parse('01/01/2011 ' + nextTime);
thisTimeNew = Date.parse('01/01/2011 ' + thisTime);
if (currentTime >= thisTimeNew && currentTime < nextTime && currentTime > prevTime) {
title = $(this).find("p").text();
if (title != $("p#playingTitle").text()) {
$("p#playingTitle").text(title);
}
}
})
}
Don’t use a formated date, just pass the Unix timestamp value to the script (don’t forget to multiply it by 1000, because JS works with milliseconds).
var serverTime = <?php echo time(); ?>;
var tmpTime = new Date(serverTime * 1000);

Different line of text each hour

I'm trying to make a site that displays a different line of text depending on the hour (GMT). I have tried using javascript, but I'm very much a beginner! I've managed to piece the following bit of code together but can't seem to get it to work. Any help appreciated!
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11)
{
document.write("<b>Paris</b>");
}
;
});
Javascript has a Date class.
var hour = new Date().getHours();
if(...) {
// do something
}
This code extract
if (hour>10 && hour<11)
can't be working with hours, because time can't be > 10 and < 11 at the same time (hour is an int).
How about:
var now = new Date();
var utcMillis = now.getTime() + now.getTimzoneOffset() * 60000;
var hour = new Date(utcMillis).getHours(); // 0-23
switch(hour) {
case 10: document.write("<b>Paris</b>"); break;
//...
}
Some good info here: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329
You could also put your phrases in an array (which you might get from the server):
var phrases = ["Hi!", "blah", "more blah", ...];
... and then you can replace the switch above with:
document.write("<b>" + phrases[hour] + "</b>");
You might want to save yourself some time and use a framework that makes things work pretty much the same way across different browsers. JQuery is my favorite, but there are plenty. Such libraries make it easy to manipulate content in your page, fetch JSON from the server, etc etc.
At first sight:
o.datetime is wrong formatted for JS Date method.
you return an instance of new Date() to get the hour use .getHours()
You can look here to find a way to convert your dateString from o.datetime How can I convert string to datetime with format specification in JavaScript?
Use time.getHours() > 12 instead of time > 12
If you use: getDateFromFormat() from http://www.mattkruse.com/javascript/date/ I think the conversion will be something like E, dd MMM hh:mm:ss +0000
SIMPLE ANSWER:
You can just parse the hour to your callback: (See your JSON here http://json-time.appspot.com/time.json?tz=GMT)
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(o.hour); // See o.hour here
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11) {
document.write("<b>Paris</b>");
}
});
I've created a quick jsfiddle page: http://jsfiddle.net/eBAGS/5/ with a demo that should do what you need. It gets the time from the users PC rather than from a server though, but it could be modified.
HTML
<button onClick="getPhrase()">Show me a phrase for this hour</button>
<div id="placeHolder"></div>
Javascript
function getPhrase() {
h = new Date().getHours(); //Get the current hour
phrase = new Array(); //Create an array of phrases
phrase[1] = 'Hello';
phrase[2] = 'there';
phrase[3] = 'this';
phrase[4] = 'will';
phrase[5] = 'show';
phrase[6] = 'a';
phrase[7] = 'different';
phrase[8] = 'message';
phrase[9] = 'depending';
phrase[10] = 'on';
phrase[11] = 'the';
phrase[12] = 'hour';
phrase[13] = 'of';
phrase[14] = 'day';
phrase[15] = 'that';
phrase[16] = 'you';
phrase[17] = 'look';
phrase[18] = 'at';
phrase[19] = 'it';
phrase[20] = '!';
phrase[21] = 'W';
phrase[22] = 'X';
phrase[23] = 'Y';
phrase[24] = 'Z';
document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}​

Categories