ls there a native way to create a time string? - javascript

I modified the code below to create a time string which looks exactly the way I want it. It is how my Timex watch displays time.
Is there a native way to do this? I feel like I must have re-invented the wheel as surely many have needed this method before me.
const api = {};
// gets a time string which is human readable using the Date object
api.getTime = function() {
const date = new Date();
// get minutes and add a 0 if needed
let min = date.getMinutes();
min = (parseInt(min, 10) < 10 ? '0' : '') + min;
// get hours, determine AM or PM and change to 12 hours
// not preceding 0 is needed
let hour = date.getHours();
const amPm = hour >= 12 ? 'PM' : 'AM';
hour = ( hour % 12 ) || 12;
// get seconds and add a 0 if needed
let sec = date.getSeconds();
sec = (parseInt(sec, 10) < 10 ? '0' : '') + sec;
return `${hour}:${min}:${sec} ${amPm}`;
}
module.exports = api;

I think it is definitely helping if you take a look at toLocaleTimeString(), from the documentation:
Return the time portion of a Date object as a string, using locale conventions.
You can test out this function as the following:
const date = new Date().toLocaleTimeString();
console.log(date);
I hope that helps!

Related

How to compare two times in javascript

I'm struggling to compare two times.
I need to print Current class going based on the current time.
Example: current time based class going on the college/school
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
Current_time = hour + ':' + min + ':' + mid;
start_time = "09:00:PM";
end_time = "10:00:PM";
if (parseInt(start_time) <= parseInt(Current_time) || parseInt(end_time) >= parseInt(Current_time)) {
console.log("C programming class is going");
} else {
console.log("No class are avalible");
}
OUTPUT:
C programming class is going....
It seems you are looking for the shortest path to have your homework done.
Please check the references for Date function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Some tips:
Make sure you understand how the Date object is created. You can use strings!
If you want to define date manually using each day, month , value, you can!
Check your strings.. are you sure "09:00:PM" is a valid string for date?
Are you sure you can use parseInt for parsing dates?
Anyway, you need to do more research.
The easiest way to check if a time is between a start and an end time is to store the time using unix time(https://en.wikipedia.org/wiki/Unix_time). It represents the time in seconds after 00:00:00 UTC on 1 January 1970. so you can do the following:
const startTime = 1624802400 // 27.6.21 16:00
const endTime = 1624809600 //27.6.21 18:00
const currentTime = Date.now()/1000
if(currentTime < endTime && currentTime > startTime){
console.log('Class is going')
}
if(currentTime > endTime){
console.log('Class ended')
}
if(currentTime < startTime){
console.log('Class has not started')
}
Date.now() returns the current time in milliseconds so you need to divide it by 1000

Display time based on my Operating System time format

I am new to coding. I know HTML, CSS, and js. My question is I want to display time in my HTML page based on Operating system time format. For example, my system time format is 12 hours format I need to show 12 hours format if my system time format is 24 hours I need to show 24 hours format in my HTML page. I test myself switch time format in OS time settings. That time also page time has to change.
Is it possible to do with HTML, CSS and js?
If not is there any alternative ways to do it. Help or suggest me
it may help
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
document.write(hours + ":" + minutes + " " + suffix)
Short answer is No, but, You can check how the system query possibilities used:
console.log(navigator)
Check this answer
Get system infos with JS Answer &
Navigator documentation
not sure if we've a function to differentiate the time format and give us output based on OS time. But just in case if you've a chance to manipulate at your end, try this using JavaScript built-in functions :
For 12-hr Format :
let formattedTime = new Date().toLocaleTimeString('en-US');
console.log(formattedTime)
For 24-hr Format :
let currentDateTime = new Date();
let formattedTime = currentDateTime.getHours() + ":" + currentDateTime.getMinutes() +":" + currentDateTime.getSeconds();
console.log(formattedTime)
(Or)
For 24-hr Format in one line as #Edson stated :
let currentDateTime = new Date();
console.log(currentDateTime.toLocaleTimeString('en-US', { hour12: false }))

Date/Time format in Javascript

I have a time string which is 01:00:00 all I want to do is convert it to 1:00 am using Javascript date time conversion.
I have tried SimpleDateFormat which gives SimpleDateFormat is not defined
Following are the links i found but could not understand or implement:
This gives Invalid Date
This gives SimpleDateFormat is not defined
This gives the same.
I just want to understand how date and time formatting works in Javascript.
I already do it in java with SimpleDateFormat, but i think it is not as easy in JS.
Please help. Thanks in Advance.
EDIT:
This link was suggested as a possible duplicate, but then the function in that answer accepts Date object. I want to convert string time to Date.
Try this , just use date object and extract hours and minutes , i think is easy to understand it
vvar str = "01:00:00"; var res = str.split(":");
document.getElementById("demo").innerHTML = res[0]; // =01
document.getElementById("demo").innerHTML = res[1]; // =00
document.getElementById("demo").innerHTML = res[2]; // =00
so in your case , should be :
var str = "01:00:00";
var res = str.split(":");
var hour = res[0]; // =01
var minutes=res[1]; // = 00
var ampm = hour >= 12 ? 'PM' : 'AM';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? minutes : minutes;
var strTime = hour + ':' + minutes + ' ' + ampm;
alert(strTime);
ps. if u wanna use java , you can do it in a jsp page where you can use java , html and javascript .

Converting isotime to shorttime in javascript

I have a ajax call which returns a time e.g 16:06:59 i want to convert it to 4:06 PM
var mydate = obj[0].time;
mydate comes 16:06:59 but when i try to use it with var date = new Date(), it gives me todays date .
Is there any solution to realize what i want ?
Thanks
The simplest answer is to split it into parts and then use them however you want, e.g.:
var parts = obj[0].time.split(":");
// parts[0] is now "16"
// parts[1] is now "06"
// parts[2] is now "59"
// Then perhaps (to get numbers and give the parts names)
var hours = parseInt(parts[0], 10);
var minutes = parseInt(parts[1], 10);
var seconds = parseInt(parts[2], 10);
...and of course for the first one you can use:
if (hours > 12) {
hours -= 12;
}
...if you want to do the a.m./p.m. thing. Just remember you did that and set your a.m./p.m. variable accordingly.
If you really want a Date instance, you can do this:
var dt = new Date();
dt.setHours(hours); // Be sure to use the real value here, not the one -12
dt.setMinutes(minutes);
dt.setSeconds(seconds);
try this :
function Convert24HoursTo12(time) {
var timeArray = time.split(':');
var hours = timeArray[0];
var minutes = timeArray[1];
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
and call it:
Convert24HoursTo12(obj[0].time);
See Demo Here.
You can do this:
"16:06:59".split(':').slice(0, 2)
.map(function (x, index) {
return index == 0 ? (x > 12 ? x - 12 + "PM" : x + "AM") : x
}).join(":").replace(/(.+?)((P|A)M)(.+)/, "$1$4 $2");
Modify the following code according to your need
var mydate= new Date();
var myhour=mydate.getHours();
var ampm="AM";
if(myhour==12)ampm="PM";
if(myhour==0)myhour=12;
if (myhour>12){
myhour-=12;
ampm="PM";
}else{
myhour=mydate.getHours();
}
var mytime=myhour+":"+mydate.getMinutes()+":"+mydate.getSeconds()+" "+ampm;
then use mytime variable anywhere you want
I have not checked it as I am in a hurry now. I hope it works well.

How to use format() on a moment.js duration?

Is there any way I can use the moment.js format method on duration objects? I can't find it anywhere in the docs and it doesn't seen to be an attribute on duration objects.
I'd like to be able to do something like:
var diff = moment(end).unix() - moment(start).unix();
moment.duration(diff).format('hh:mm:ss')
Also, if there are any other libraries which can easily accommodate this sort of functionality, I'd be interested in recommendations.
Thanks!
// set up
let start = moment("2018-05-16 12:00:00"); // some random moment in time (in ms)
let end = moment("2018-05-16 12:22:00"); // some random moment after start (in ms)
let diff = end.diff(start);
// execution
let f = moment.utc(diff.asMilliseconds()).format("HH:mm:ss.SSS");
alert(f);
Have a look at the JSFiddle
convert duration to ms and then to moment:
moment.utc(duration.as('milliseconds')).format('HH:mm:ss')
We are looking into adding some kind of formatting to durations in moment.js. See https://github.com/timrwood/moment/issues/463
A couple other libraries that might help out are http://countdownjs.org/ and https://github.com/icambron/twix.js
Use this plugin Moment Duration Format.
Example:
moment.duration(123, "minutes").format("h:mm");
Use this line of code:
moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")
var diff = moment(end).unix() - moment(start).unix();
moment.utc(moment.duration(diff).asMilliseconds()).format("HH:mm:ss.SSS");
The best scenario for my particular use case was:
var duration = moment.duration("09:30"),
formatted = moment.utc(duration.asMilliseconds()).format("HH:mm");
This improves upon #Wilson's answer since it does not access private internal property _data.
You don't need .format. Use durations like this:
const duration = moment.duration(83, 'seconds');
console.log(duration.minutes() + ':' +duration.seconds());
// output: 1:23
I found this solution here: https://github.com/moment/moment/issues/463
EDIT:
And with padding for seconds, minutes and hours:
const withPadding = (duration) => {
if (duration.asDays() > 0) {
return 'at least one day';
} else {
return [
('0' + duration.hours()).slice(-2),
('0' + duration.minutes()).slice(-2),
('0' + duration.seconds()).slice(-2),
].join(':')
}
}
withPadding(moment.duration(83, 'seconds'))
// 00:01:23
withPadding(moment.duration(6048000, 'seconds'))
// at least one day
I needed to do this for work as a requirement to display the hours in this format.
At first I tried this.
moment.utc(totalMilliseconds).format("HH:mm:ss")
However anything over 24 hours and the hours reset to 0.
But the minutes and seconds were accurate.
So I used only that part for the minutes and seconds.
var minutesSeconds = moment.utc(totalMilliseconds).format("mm:ss")
Now all I need is the total hours.
var hours = moment.duration(totalMilliseconds).asHours().toFixed()
And to get that format that we all want we just glue it together.
var formatted = hours + ":" + minutesSeconds
if totalMilliseconds is 894600000 this will return 249:30:00.
Hope that helped. Leave any questions in the comments. ;)
I use:
var duration = moment.duration("09:30");
var str = moment(duration._data).format("HH:mm");
And I get "09:30" in var str.
if diff is a moment
var diff = moment(20111031) - moment(20111010);
var formated1 = moment(diff).format("hh:mm:ss");
console.log("format 1: "+formated1);
If you're willing to use a different javascript library, numeral.js can format seconds as follows (example is for 1000 seconds):
var string = numeral(1000).format('00:00');
// '00:16:40'
If all hours must be displayed (more than 24) and if '0' before hours is not necessary, then formatting can be done with a short line of code:
Math.floor(duration.as('h')) + moment.utc(duration.as('ms')).format(':mm:ss')
Based on ni-ko-o-kin's answer:
meassurements = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"];
withPadding = (duration) => {
var step = null;
return meassurements.map((m) => duration[m]()).filter((n,i,a) => {
var nonEmpty = Boolean(n);
if (nonEmpty || step || i >= a.length - 2) {
step = true;
}
return step;
}).map((n) => ('0' + n).slice(-2)).join(':')
}
duration1 = moment.duration(1, 'seconds');
duration2 = moment.duration(7200, 'seconds');
duration3 = moment.duration(604800, 'seconds');
withPadding(duration1); // 00:01
withPadding(duration2); // 02:00:00
withPadding(duration3); // 01:07:00:00:00
I use the classic format function in these cases:
var diff = moment(end).unix() - moment(start).unix();
//use unix function instead of difference
moment.unix(diff).format('hh:mm:ss')
This is a hack because the time diff is treated as a standard moment date, an early epoch date time, but it doesn't matter to our goal and you don't need any plugin
Short version (one-liner):
moment.duration(durationInMs).asHours()|0||"00" + ":" + moment.utc(durationInMs).format("mm:ss")
Extended version:
export const formatDuration = (durationInMs) => {
const hours = Math.floor(moment.duration(durationInMs).asHours()) || "00"
return hours + ":" + moment.utc(durationInMs).format("mm:ss")
}
Example cases:
To format moment duration to string
var duration = moment.duration(86400000); //value in milliseconds
var hours = duration.hours();
var minutes = duration.minutes();
var seconds = duration.seconds();
var milliseconds = duration.milliseconds();
var date = moment().hours(hours).minutes(minutes).seconds(seconds).millisecond(milliseconds);
if (is12hr){
return date.format("hh:mm:ss a");
}else{
return date.format("HH:mm:ss");
}
if you use angular add this to your filters:
.filter('durationFormat', function () {
return function (value) {
var days = Math.floor(value/86400000);
value = value%86400000;
var hours = Math.floor(value/3600000);
value = value%3600000;
var minutes = Math.floor(value/60000);
value = value%60000;
var seconds = Math.floor(value/1000);
return (days? days + ' days ': '') + (hours? hours + ' hours ': '') + (minutes? minutes + ' minutes ': '') + (seconds? seconds + ' seconds ': '')
}
})
usage example
<div> {{diff | durationFormat}} </div>
My solution that does not involve any other library and it works with diff > 24h
var momentInSeconds = moment.duration(n,'seconds')
console.log(("0" + Math.floor(momentInSeconds.asHours())).slice(-2) + ':' + ("0" + momentInSeconds.minutes()).slice(-2) + ':' + ("0" + momentInSeconds.seconds()).slice(-2))
How to correctly use moment.js durations?
|
Use moment.duration() in code
First you need to import moment and moment-duration-format.
import moment from 'moment';
import 'moment-duration-format';
Then, use duration function. Let us apply the above example: 28800 = 8 am.
moment.duration(28800, "seconds").format("h:mm a");
🎉Well, you do not have above type error. 🤔Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.
💡The solution is to transform seconds to milliseconds and use UTC time.
moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')
All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp
const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')
How about native javascript?
var formatTime = function(integer) {
if(integer < 10) {
return "0" + integer;
} else {
return integer;
}
}
function getDuration(ms) {
var s1 = Math.floor(ms/1000);
var s2 = s1%60;
var m1 = Math.floor(s1/60);
var m2 = m1%60;
var h1 = Math.floor(m1/60);
var string = formatTime(h1) +":" + formatTime(m2) + ":" + formatTime(s2);
return string;
}
Use moment-duration-format.
Client Framework (ex: React)
import moment from 'moment';
import momentDurationFormatSetup from 'moment-duration-format';
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
Server (node.js)
const moment = require("moment-timezone");
const momentDurationFormatSetup = require("moment-duration-format");
momentDurationFormatSetup(moment);
const breakLengthInMinutes = moment.duration(breakLengthInSeconds, 's').format('m');
moment.duration(x).format() has been deprecated.
You can usemoment.utc(4366589).format("HH:mm:ss") to get the desired response.
console.log(moment.utc(4366589).format("HH:mm:ss"))
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
const duration = moment.duration(62, 'hours');
const n = 24 * 60 * 60 * 1000;
const days = Math.floor(duration / n);
const str = moment.utc(duration % n).format('H [h] mm [min] ss [s]');
console.log(`${days > 0 ? `${days} ${days == 1 ? 'day' : 'days'} ` : ''}${str}`);
Prints:
2 days 14 h 00 min 00 s
There is no longer (if there ever was) any need to convert duration to utc to solve this issue. This is like converting a base10 "1" to binary and then saying that since output "1" looks like base10 we'll have no issues assuming this is a base10 value for any further operations.
Use moment-duration-format and note that with { trim: false } you can prevent trimming:
moment.duration(1000000, "seconds").format("hh:mm:ss", { trim: false })
> "277:46:40"
moment.duration(0, "seconds").format("hh:mm:ss", { trim: false })
> "00:00:00"
Let's compare this with the not recommended method of using abusing utc:
moment.utc(moment.duration(1000000, "seconds").asMilliseconds()).format('HH:mm:ss')
> "13:46:40"
Just moment.js without any other plugins
moment().startOf('day').seconds(duration).format('HH:mm:ss')
import * as moment from 'moment'
var sleep = require('sleep-promise');
(async function () {
var t1 = new Date().getTime();
await sleep(1000);
var t2 = new Date().getTime();
var dur = moment.duration(t2-t1);
console.log(`${dur.hours()}h:${dur.minutes()}m:${dur.seconds()}s`);
})();
0h:0m:1s
You can use numeral.js to format your duration:
numeral(your_duration.asSeconds()).format('00:00:00') // result: hh:mm:ss
This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.
/**
* PT1H30M -> 0130
* #param {ISO String} isoString
* #return {string} absolute 4 digit number HH:mm
*/
const parseIsoToAbsolute = (isoString) => {
const durations = moment.duration(isoString).as('seconds');
const momentInSeconds = moment.duration(durations, 'seconds');
let hours = momentInSeconds.asHours().toString().length < 2
? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();
if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);
const minutes = momentInSeconds.minutes().toString().length < 2
? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();
const absolute = hours + minutes;
return absolute;
};
console.log(parseIsoToAbsolute('PT1H30M'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
If you use Angular >2, I made a Pipe inspired by #hai-alaluf answer.
import {Pipe, PipeTransform} from "#angular/core";
#Pipe({
name: "duration",
})
export class DurationPipe implements PipeTransform {
public transform(value: any, args?: any): any {
// secs to ms
value = value * 1000;
const days = Math.floor(value / 86400000);
value = value % 86400000;
const hours = Math.floor(value / 3600000);
value = value % 3600000;
const minutes = Math.floor(value / 60000);
value = value % 60000;
const seconds = Math.floor(value / 1000);
return (days ? days + " days " : "") +
(hours ? hours + " hours " : "") +
(minutes ? minutes + " minutes " : "") +
(seconds ? seconds + " seconds " : "") +
(!days && !hours && !minutes && !seconds ? 0 : "");
}
}

Categories

Resources