This question already has answers here:
convert 12-hour hh:mm AM/PM to 24-hour hh:mm
(38 answers)
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
How to force addition instead of concatenation in javascript [duplicate]
(3 answers)
Closed 2 years ago.
So I have a time array which holds slot time. I am trying to convert 12 hr format to 24 hr format but it is not working
Here is what I have tried so far:
let timeArray = ["11:12 AM", "11:13 AM", "1:14 PM"];
for (i in timeArray) {
let [time, mod] = timeArray[i].split(" ");
let [hr, min] = time.split(":");
if (hr < 12) {
hr = hr + 12;
}
console.log(hr);
}
Here is the output:
The expected output should add 12 to hr number to convert it to 24 hr format.
I would suggest you use moment.js ( https://momentjs.com/ )
You can play with date and time object in numerous way you want by using moment.js
Use parseInt to convert the string to an integer.
let timeArray = ["11:12 AM", "11:13 AM", "1:14 PM"];
for (i in timeArray) {
let [hr, min] = timeArray[i].split(":");
if (hr < 12) {
hr = parseInt(hr) + 12;
}
console.log(hr);
}
Related
This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
How to get difference between 2 Dates in Years, Months and days using moment.js
(3 answers)
How to get the difference of two dates in mm-dd-hh format in Javascript
(3 answers)
Closed 2 years ago.
I am trying to get the difference between two dates (my birthday and the current date to get the time left until my birthday), But I want the output format in ('Year/Months/Days); How can I do that? that's what I've tried so far :
const birthday = new Date ('11-20-2021').getTime();
const today = new Date ().getTime();
const dys = (1000*60*60*24);
const months = (dys*30);
let differance = birthday-today ;
const formatted = Math.round(differance/dys);
console.log(formatted);`
thank you in advance
How do you feel about the modulo operator? :)
This is a common math operation, like finding change or such. Think of it this way, if you have a large number of days, say 397, you can get number of years by doing integer division (1), then you can get the number of days left by doing modulo by a year to get the remainder (in days) 397%365 = 32. Then you can repeat the process to get number of months remaining (1...assuming 30 day month) in that and again, modulo to get the final number of days 2 ...
I'm no javascript pro, but I think you need to use Math.floor(quotient) to get the result of division in integer format.
this example compares between the current date and the date 2100/0/14 try the same concept in the example and i hope it helps:
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
Working with dates and differences can be difficult because there are a lot of edge cases. which is why I prefer to let a dedicated library handle this, like https://momentjs.com/
moment has a plugin (https://www.npmjs.com/package/moment-precise-range-plugin) which does exactly what you are looking for:
import moment from 'moment';
import 'moment-precise-range-plugin';
var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5}
var str = `Years: ${diff.years}, Months: ${diff.months}, Days: ${diff.days} `; // 'Years: 0, Months: 1, Days: 2'
If I got you right, I've done it this way.
Haven't touched your original code, but added a function that calculates the dateTime output of the total days of difference.
const birthday = new Date('11-20-2021').getTime();
const today = new Date().getTime();
const dys = (1000 * 60 * 60 * 24);
const months = (dys * 30);
let totalDayserance = birthday - today;
const formatted = daysToDateTime(totalDayserance / dys);
console.log(formatted);
function daysToDateTime(totalDays) {
var baseVal = '';
var formedValues = [
['Years', 365],
['Months', 30],
['Days', 1]
];
for (var i = 0; i < formedValues.length; i++) {
var valueByGroup = Math.floor(totalDays / formedValues[i][1]); //by months
if (valueByGroup >= 1) {
baseVal += (valueByGroup + formedValues[i][0]) + ', ';
totalDays -= valueByGroup * formedValues[i][1];
}
}
return baseVal;
}
This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 3 years ago.
So,
I have this
10 Dec, 2019T14:07:21
format of date coming from backend , what I need is to find how many days ago.
like today is 20 , so for todays date it will give 0 days ago.
You can try this code.
var date1 = new Date("12/13/2010");
var date2 = new Date("12/20/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10);
console.log(diffDays )
You can compare two dates. Substracting them will give you the miliseconds difference. THose miliseconds can be converted into days.
const now = new Date();
// Mimick a backend date
const daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate() - 10);
// Compare both, outputs in miliseconds
const diffMs = now - daysAgo;
// Get the number of days by dividing by the miliseconds in a single day
const daysDiff = Math.round(diffMs/(1000*60*60*24));
console.log(daysDiff)
(new Date()-new Date("10 Dec, 2019T14:07:21".replace("T"," ")))/1000/60/60/24
What you try to do is called "date diff" meaning you want to find the difference in days between 2 dates. First of all you need to create a new Date object from the string you want. You can do that using Moment.js library that will parse your date string and return a Date object.
var date1 = moment("10 Dec, 2019T14:07:21", "DD MMM, YYYY");
var date2 = new Date() //today date
A simple js function accomplishing that is the one below
function dateDiff(date1, date2) {
var datediff = date1.getTime() - date2.getTime();
return (datediff / (24*60*60*1000));
}
dateDiff function will return the difference between dates, so if date1 is a previous day, it will return a negative number of days. In order to convert it to the "x days ago" format you need, you need to simply multiply the result by -1.
This question already has answers here:
How do I use .toLocaleTimeString() without displaying seconds?
(13 answers)
How do you display JavaScript datetime in 12 hour AM/PM format?
(31 answers)
Closed 3 years ago.
I want to get a JavaScript code that displays only hour, minute and AM or PM. I don't want seconds.
This is the code i have so far:
var d = new Date();
document.getElementById("time").innerHTML = d.toLocaleTimeString();
Date objects have getHours() and getMinutes() methods.
getHours() returns values in the range of [0, 23], meaning you can compare with 12 to determine 'am' or 'pm'.
Lastly, consider using mdn as a helpful reference about the standard API.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
let d = new Date('December 17, 1995 22:11:51');
let pm = d.getHours() >= 12;
let hour12 = d.getHours() % 12;
if (!hour12)
hour12 += 12;
let minute = d.getMinutes();
console.log(`${hour12}:${minute} ${pm ? 'pm' : 'am'}`);
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
I am having issues in comparing date formats:
05/31/2017 10:50 AM (IST) and 20170531 003837.000(EST) using Date.parse. Any leads on this?.
//Capture input for debug
var Outlmd = "05/31/2017 10:50 AM";
var Outlsr = "20170531 003837.000";
//Convert to internal format - milliseconds since epoch
d1 = Date.parse(05/31/2017 10:50 AM);
d2 = Date.parse(20170531 003837.000);
if(d1 > d2) { NewTempDate = lmd; } else { NewTempDate = lsr; }
You forgot quotes within Date.parse
Do Date.parse('05/31/2017 10:50 AM')
Update
Please consider the code below:
//Capture input for debug
var lmd = "05/31/2017 10:50 AM";
var lsr = "2017-05-31T00:45:25-0400";
//Convert to internal format - milliseconds since epoch
d1 = Date.parse(lmd);
d2 = Date.parse(lsr);
if(d1 > d2) { NewTempDate = lmd; } else { NewTempDate = lsr; }
Please note that lmd and lsr should be parsable data string without extra spaces: "2017-05-31T00:45:25-0400" not " 2017-05-31T00:45:25-0400"
This question already has answers here:
convert 12-hour hh:mm AM/PM to 24-hour hh:mm
(38 answers)
Closed 8 years ago.
I have the time which is in the format "07:30PM" .I need to convert into 24 hr format using javascript to do further calculations.Please assist me in doing this.
Duplicate of
this
Simple solution:
function ampmTo24(time)
{
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AP = time.match(/\s(.*)$/);
if (!AP) AP = time.slice(-2);
else AP=AP[1];
if(AP == "PM" && hours<12) hours = hours+12;
if(AP == "AM" && hours==12) hours = hours-12;
var Hours24 = hours.toString();
var Minutes24 = minutes.toString();
if(hours<10) Hours24 = "0" + Hours24;
if(minutes<10) Minutes24 = "0" + Minutes24;
return Hours24 + ":" + Minutes24
}