How to get right format in moment js - javascript

i need to convert input value: ":2" to 'HH:mm' format.
":2" it should be converted to "00:20". All this process should be done with moment.js
let timeString = ":2";
const time = document.getElementById('time');
time.innerHTML = moment(timeString).format('HH:mm');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<span id="time"></span>
I didn't put input, because my problem is to get or convert correct format.

As stated before, you will have to convert the input yourself before passing it to momentjs - the following could work for you, depending on what the result for other values should be. I assumed:
":3" -> "00:30",
":21" -> "00:21",
"2:2" -> "02:20"
let timeString = ":2";
const hours = timeString.split(":")[0] || "00";
let minutes = timeString.split(":")[1];
if (minutes.length === 1) {
minutes = minutes * 10;
}
const parsedTime = hours + ":" + minutes;
const time = document.getElementById('time');
time.innerHTML = moment(parsedTime, "HH:mm").format("HH:mm");

Related

Difference between two timestamps in hours minutes and seconds

I am trying to calculate the difference between two timestamp
"2020-03-18T17:34:45.856Z", "2020-03-18T16:34:45.856Z"
the difference should be like this: 2 hours 20min 30sec
I have tried using
return moment.utc(moment(startDate, 'HH:mm:ss').diff(moment(endDate, 'HH:mm:ss'))).format('HH:mm:ss');
m not sure how to get the desired format
You need to get it manually using Moment Duration
const startDate = "2020-03-18T17:34:45.856Z";
const endDate = "2020-03-18T16:34:45.856Z";
const diff = moment(startDate).diff(moment(endDate));
const duration = moment.duration(diff);
const hrs = duration.hours();
const mins = duration.minutes();
const secs = duration.seconds();
console.log(hrs + "hours " + mins + "min " + secs + "sec");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Get System time, localstorage, compare dates and performe an action

I need to get the system time once, then store it on localStorage, then compare this stored value with a further system date and then perform an action if the future date is equal or greater than the one which is stored. I have tried but I am stucked in making the function which gets the system time the first time to run only once so I can get a future date to compare.
This is my code
console.log(formatTime());
function formatTime() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
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;
return (strTime = date.getDay() + "/" + date.getMonth() + "/" + date.getFullYear() + " " + hours + ":" + minutes + ":" + seconds + " " + ampm);
}
document.getElementById("currentdt").innerHTML = strTime;
var strTime1 = formatTime();
var timeString = JSON.stringify(strTime1);
localStorage.setItem("strTime1", timeString);
var timeStringFromLocalStorage = localStorage.getItem("strTime1");
var timeFromLocalStorage = JSON.parse(timeStringFromLocalStorage);
document.getElementById("time").innerHTML = strTime1;
console.log(timeStringFromLocalStorage);
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA, "strTime1");
var momentB = moment(dateTimeB, "strTime");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("strTime1", "strTime"));
The function below will check if there has been a value set in localStorage. If there is no value set, it will set its first and stop the function.
If there is a value, then it will be turned into a moment instance and compared with the current date. If a difference in days is equal or larger to than specified it will redirect the page.
function redirectWhenOlderThan(days, url) {
const storedValue = localStorage.getItem('first-visit');
const now = moment();
/**
* If nothing is stored yet, then storedValue will be null.
* Here you will set the first localStorage item for the first time.
* Instead of a full date, store the timestamp.
* Then stop the function.
*/
if (storedValue === null) {
localStorage.setItem('first-visit', now.valueOf().toString());
return;
}
/**
* If there is a stored value then it will be a timestamp as a string.
* First parse it into a number before putting it into moment.
* Then check the difference in days between the dates.
*/
const then = moment(Number(storedValue));
const difference = now.diff(then, 'days');
/**
* If the difference is higher or equal to the given days, redirect.
*/
if (difference >= days) {
location.href = url;
}
}
Call the function with amount of days that should have passed since the first visit and the URL to redirect to.
redirectWhenOlderThan(15, 'https://example.com');
I hope this is what you meant.
Sidenote: dive into moment.js if you have the time. It has a lot of features that could spare you some time, like your formatTime() function, it can be written in a single line with moment.
moment().format('DD/MM/YYYY h:mm:ss A');
Now the final code goes like this
function formatTime() {
var date = new Date();
return strTime = date.getDay() + '/' + date.getMonth()+'/'+date.getFullYear();
}
document.getElementById("currentdt").innerHTML = strTime;
function redirectWhenOlderThan(days, url) {
const storedValue = localStorage.getItem('first-visit');
const now = moment();
if (storedValue === null) {
localStorage.setItem('first-visit', now.valueOf().toString());
return;
}
const then = moment(Number(storedValue));
const difference = now.diff(then, 'days');
if (difference >= days) {
location.href = url;
}
else {
window.location.href= 'app/phr.html';
}
}
setTimeout(function () {
redirectWhenOlderThan(1, 'app/licences.html');
}, 3000);

How to add hours to string formatted as HH:MM:SS in 24 hour format

I'm trying to add hours to time in the format of 24 hours say '23:59:59'. I need to add, for example, 2.5 hours so the time should roll to the next day and be shown as '02:30:00'.
What I have tried so far works until it reaches '23:59:59'. I need to show the next day time if it exceeds '23:59:59'. Here is what I have tried so far:
var time = $('#starttime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var time2 = $('#endtime').val().split(':');
var endtimeval = new Date();
endtimeval.setHours(+time2[0]);
endtimeval.setMinutes(time2[1]);
endtimeval.setSeconds(time2[2]);
var str = d.getHours() + parseInt($('#noofhours').val()) + ":" + time2[1] + ":" + time2[2];
$('#endtime').val(str);
Using a Date Object here is possibly unnecessary, modulo arithmetic should suffice.
const pad = n => {
const s = String(n);
return s.length > 1 ? s : '0' + s;
};
const addHours = (timeVal, numHours) => {
const [hr, min, sec] = timeVal.split(':').map(Number);
const [,lefty, righty] = String(numHours).match(/(\d+)(?:(\.\d+))?/).map(Number);
const hours = (hr + lefty) % 24;
const minutes = righty === undefined ?
min :
((righty * 60 | 0) + min) % 60;
return [hours, minutes, sec].map(pad).join(':');
};
addHours('23:59:59', 2.5) // "01:29:59"
Note that since there's no dates involved it will not accurately handle e.g. daylight savings time. Also note that minutes are in this example rounded down, you could repeat the logic for seconds if desired.
Note that your approach using Date objects will give different answers for the same inputs depending on when/where the logic runs, for the same reasons.
Make a custom date adder?
const add = (time, hours) => {
let [hh, mm, ss] = time.split(':');
const seconds = hours * 60 * 60;
ss = ss * 1 + seconds;
if (ss >= 60) {
mm = mm * 1 + ss / 60;
ss = (ss % 60).toPrecision(2).padStart(2, '0');
}
if (mm >= 60) {
hh = hh * 1 + mm / 60;
mm = (mm % 60).toPrecision(2).padStart(2, '0');
}
hh = (Math.floor(hh) % 24).toString().padStart(2, '0');
return hh + ':' + mm + ':' + ss;
}
console.log(add("23:59:59", 2.5));
you may apply DRY principle and refactor the code yourself. But it will get the job done according to your requirement.
The simple trick that I did is just converted the hours entered as float/int to a minute value by multiplying to 60 and created a date, with this just added the time I already have.
Here the solution with minimal steps:
var time = $('#endtime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var addeddate = new Date();
addeddate.setMinutes(parseFloat($('#noofhours').val()) * 60);
$('#endtime').val(("0" + (addeddate.getHours())).slice(-2) + ":" + ("0" + (addeddate.getMinutes())).slice(-2) + ":" + ("0" + (addeddate.getSeconds())).slice(-2)); //The answer that I needed in endtime id value.
You can use vanilla JavaScript Date methods fairly easily here. Most of the work is parsing the time string inputs and then concatenating the time string output. For example:
const start = '23:59:59';
const add = '2.5';
const [hh, mm, ss] = start.split(':').map(x => parseInt(x));
const d = new Date(new Date().setHours(hh, mm + (add * 60), ss));
const end = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(end);
// 2:29:59

Display epoch time as HHMM format in javascript

I have a variable that contains epoch time. I want to display the time in HHMM format.
Here is my code;
function epoch_time_to_date_obj(epoch_time)
{
var utcSeconds = epoch_time;
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
return d;
}
let epoch_time = 1234567890;
let date_obj = epoch_time_to_date_obj(epoch_time);
I would like to extract the HHMM time information from date_obj and display the time in HHMM format in Hong Kong time.
I am using node.js v6
let epoch_time = 1234567890 * 1000;
var date_obj = new Date(epoch_time);
const hrs = date_obj.getHours();
const mins = date_obj.getMinutes();
let hhmm = (hrs < 10 ? "0" + hrs : hrs) + ":" + (mins < 10 ? "0" + mins : mins);
alert(hhmm);

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;

Categories

Resources