Converting isotime to shorttime in javascript - 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.

Related

ls there a native way to create a time string?

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!

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 .

Get the time elapsed between two timestamps and convert it to date [duplicate]

I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.
Example:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
//expected result:
"00:39:30"
what I tried:
var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");
console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30
I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.
The result of moment.duration(now.diff(then)) is a duration with the correct internal values:
days: 0
hours: 0
milliseconds: 0
minutes: 39
months: 0
seconds: 30
years: 0
So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use
duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")
but i feel that there is something more elegant that I am completely missing.
update
looking closer, in the above example now is:
Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}
and moment(moment.duration(now.diff(then))) is:
Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}
I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(
update 2
well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.
This approach will work ONLY when the total duration is less than 24 hours:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
// outputs: "00:39:30"
If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.
If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
// outputs: "48:39:30"
Note that I'm using the utc time as a shortcut. You could pull out d.minutes() and d.seconds() separately, but you would also have to zeropad them.
This is necessary because the ability to format a duration objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
// outputs: "48:39:30"
Your problem is in passing the result of moment.duration() back into moment() before formatting it; this results in moment() interpreting it as a time relative to the Unix epoch.
It doesn't give you exactly the format you're looking for, but
moment.duration(now.diff(then)).humanize()
would give you a useful format like "40 minutes". If you're really keen on that specific formatting, you'll have to build a new string yourself. A cheap way would be
[diff.asHours(), diff.minutes(), diff.seconds()].join(':')
where var diff = moment.duration(now.diff(then)). This doesn't give you the zero-padding on single digit values. For that, you might want to consider something like underscore.string - although it seems like a long way to go just for a few extra zeroes. :)
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1
Worked for me
See more in
http://momentjs.com/docs/#/displaying/difference/
If you want difference of two timestamp into total days,hours and minutes only, not in months and years .
var now = "01/08/2016 15:00:00";
var then = "04/02/2016 14:20:30";
var diff = moment.duration(moment(then).diff(moment(now)));
diff contains 2 months,23 days,23 hours and 20 minutes. But we need result only in days,hours and minutes so the simple solution is:
var days = parseInt(diff.asDays()); //84
var hours = parseInt(diff.asHours()); //2039 hours, but it gives total hours in given miliseconds which is not expacted.
hours = hours - days*24; // 23 hours
var minutes = parseInt(diff.asMinutes()); //122360 minutes,but it gives total minutes in given miliseconds which is not expacted.
minutes = minutes - (days*24*60 + hours*60); //20 minutes.
Final result will be : 84 days, 23 hours, 20 minutes.
When you call diff, moment.js calculates the difference in milliseconds.
If the milliseconds is passed to duration, it is used to calculate duration which is correct.
However. when you pass the same milliseconds to the moment(), it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT).
That is why you get 1969 as the year together with wrong hour.
duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")
So, I think this is how you should do it since moment.js does not offer format function for duration. Or you can write a simple wrapper to make it easier/prettier.
This should work fine.
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());
If we want only hh:mm:ss, we can use a function like that:
//param: duration in milliseconds
MillisecondsToTime: function(duration) {
var seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24)
, days = parseInt(duration/(1000*60*60*24));
var hoursDays = parseInt(days*24);
hours += hoursDays;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
Use this:
var duration = moment.duration(endDate.diff(startDate));
var aa = duration.asHours();
Instead of
Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")
It's better to do
moment.utc(total.asMilliseconds()).format("HH:mm:ss");
This will work for any date in the format YYYY-MM-DD HH:mm:ss
const moment=require("moment");
let startDate=moment("2020-09-16 08:39:27");
const endDate=moment();
const duration=moment.duration(endDate.diff(startDate))
console.log(duration.asSeconds());
console.log(duration.asHours());
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
Typescript: following should work,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};
DATE TIME BASED INPUT
var dt1 = new Date("2019-1-8 11:19:16");
var dt2 = new Date("2019-1-8 11:24:16");
var diff =(dt2.getTime() - dt1.getTime()) ;
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var response = {
status : 200,
Hour : hours,
Mins : mins
}
OUTPUT
{
"status": 200,
"Hour": 0,
"Mins": 5
}
The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):
// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');
// Getting the difference: hours (h), minutes (m) and seconds (s)
let h = end.diff(start, 'hours');
let m = end.diff(start, 'minutes') - (60 * h);
let s = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);
// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);
console.log(`${hh}:${mm}:${ss}`); // 00:39:30
This will return biggest time period diff like (4 seconds, 2 minutes, 1 hours, 2 days, 3 weeks, 4 months, 5 years).
I use this for notification recent time.
function dateDiff(startDate, endDate) {
let arrDate = ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
let dateMap = arrDate.map(e => moment(endDate).diff(startDate, e));
let index = 6 - dateMap.filter(e => e == 0).length;
return {
type: arrDate[index] ?? "seconds",
value: dateMap[index] ?? 0
};
}
Example:
dateDiff("2021-06-09 01:00:00", "2021-06-09 04:01:01")
{type: "hours", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-12 04:01:01")
{type: "days", value: 3}
dateDiff("2021-06-09 01:00:00", "2021-06-09 01:00:10")
{type: "seconds", value: 10}
I create a simple function with typescript
const diffDuration: moment.Duration = moment.duration(moment('2017-09-04 12:55').diff(moment('2017-09-02 13:26')));
setDiffTimeString(diffDuration);
function setDiffTimeString(diffDuration: moment.Duration) {
const str = [];
diffDuration.years() > 0 ? str.push(`${diffDuration.years()} year(s)`) : null;
diffDuration.months() > 0 ? str.push(`${diffDuration.months()} month(s)`) : null;
diffDuration.days() > 0 ? str.push(`${diffDuration.days()} day(s)`) : null;
diffDuration.hours() > 0 ? str.push(`${diffDuration.hours()} hour(s)`) : null;
diffDuration.minutes() > 0 ? str.push(`${diffDuration.minutes()} minute(s)`) : null;
console.log(str.join(', '));
}
// output: 1 day(s), 23 hour(s), 29 minute(s)
for generate javascript https://www.typescriptlang.org/play/index.html
InTime=06:38,Outtime=15:40
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
EPOCH TIME DIFFERENCE USING MOMENTJS:
To Get Difference between two epoch times:
Syntax:
moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()
Difference in Hours:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()
Difference in minutes:
moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()
Note: You could remove .toFixed() if you need precise values.
Code:
const moment = require('moment')
console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')
Refer working example here:
https://repl.it/repls/MoccasinDearDimension
To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is
const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()
you can change the difference format as you need by just replacing the asMinutes() function
If you want a localized number of days between two dates (startDate, endDate):
var currentLocaleData = moment.localeData("en");
var duration = moment.duration(endDate.diff(startDate));
var nbDays = Math.floor(duration.asDays()); // complete days
var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);
nbDaysStr will contain something like '3 days';
See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.
It is very simple with moment
below code will return diffrence in hour from current time:
moment().diff('2021-02-17T14:03:55.811000Z', "h")
const getRemainingTime = (t2) => {
const t1 = new Date().getTime();
let ts = (t1-t2.getTime()) / 1000;
var d = Math.floor(ts / (3600*24));
var h = Math.floor(ts % (3600*24) / 3600);
var m = Math.floor(ts % 3600 / 60);
var s = Math.floor(ts % 60);
console.log(d, h, m, s)
}

Javascript format date / time [duplicate]

This question already has answers here:
Formatting the date time with Javascript
(12 answers)
Closed 8 years ago.
I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm
Can this be done using javascript's Date object?
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
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;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/
Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
Luxon: [CDN] | [Source] | [Minified]
Moment.js: [CDN] | [Source] | [Minified]
Datejs: [CDN] | [Source] | [Alpha1.zip (1.6MB)]
Demo
Update: I wrote a one-liner using Moment.js Luxon below.
const { DateTime } = luxon;
const value = DateTime
.fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.toFormat('MM/dd/yyyy h:mm a');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>
Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.
const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.
function formatDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1, // months are zero indexed
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
minuteFormatted = minute < 10 ? "0" + minute : minute,
morning = hour < 12 ? "am" : "pm";
return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
minuteFormatted + morning;
}
You can do that:
function formatAMPM(date) { // This is to display 12 hour format like you asked
var hours = date.getHours();
var minutes = date.getMinutes();
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;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);
Fiddle

Store meridiem in a variable

I am using the following code:
var myDate= new Date();
myDate.toLocaleString( );
var x= myDate.getDay();
var y=myDate.gethours();
var z=myDate.getMinutes();
The time is in 12 hour format.
Now I need to store meridiem (AM or PM) in a variable. How can I do that?
How about this:
var y=myDate.getHours();
var meridiem = (y<12)?"AM":"PM";
alert(meridiem)
getHours() returns the hour in a 24 hour format. A quick solution would be:
var meridiem = (y >= 12) ? "PM" : "AM";
Wrapped into a nice tiny function!
function getMeridiem()
{
var d = new Date();
return (d.getHours() < 12) ? 'AM':'PM';
}

Categories

Resources