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"
Related
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);
}
This question already has answers here:
Get String in YYYYMMDD format from JS date object?
(53 answers)
Closed 5 years ago.
Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings.
For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.
i tried:
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
a = new Date(userDate);
y = a.getFullYear();
m = a.getMonth();
d = a.getDate();
return y.toString() + m.toString() + d.toString();
}
console.log(formatDate("12/31/2014"));
where is the problem??
The issue is that getMonth() returns a month index from 0 to 11, so December appears as 11 and not 12.
String#split() the date on / and then concat the generated date, month and year.
function AddLeadingZero(num) {
return (num < 10 ? '0' : '') + num;
}
function formatDate(userDate) {
var [month, day, year] = userDate.split('/');
return year + AddLeadingZero(month) + AddLeadingZero(day);
}
console.log(formatDate("12/31/2014"));
console.log(formatDate("10/1/2014"));
var convertDate = function(usDate) {
var dateParts = usDate.split(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
return dateParts[3] + dateParts[1] + dateParts[2];
}
var inDate = "12/31/2014";
var outDate = convertDate(inDate);
alert(outDate);
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
Really not sure where I'm going wrong here.
I have some JavaScript to sort a table by date value:
function sortByDate() {
if (jQuery("#web-orders .data-table tbody").length > 0) {
var tbody = document.querySelector("#web-orders .data-table tbody");
var rows = [].slice.call(tbody.querySelectorAll("tr"));
}
if (jQuery("#store-orders .data-table tbody").length > 0) {
var tbodyStore = document.querySelector("#store-orders .data-table tbody");
var rowsStore = [].slice.call(tbodyStore.querySelectorAll("tr"));
rowsStore.forEach(function (entry) {
rows.push(entry);
});
}
rows.sort(function (a, b) {
console.log("a.cells[2].innerHTML = " + a.cells[2].innerHTML);
console.log("b.cells[2].innerHTML = " + b.cells[2].innerHTML);
a = new Date(Date.parse(a.cells[2].innerHTML));
b = new Date(Date.parse(b.cells[2].innerHTML));
console.log("a = " + a);
console.log("b = " + b);
return a - b;
});
rows.forEach(function (v) {
tbody.appendChild(v); // note that .appendChild() *moves* elements
});
}
Now here is some of the console output with the invalid dates:
a.cells[2].innerHTML = 28/11/2017 1:49:37 PM
b.cells[2].innerHTML = 5/09/2017 6:27:35 AM
a = Invalid Date
b = Tue May 09 2017 06:27:35 GMT+0930 (Cen. Australia Standard Time)
a.cells[2].innerHTML = 28/11/2017 1:49:37 PM
b.cells[2].innerHTML = 24/09/2017 6:12:48 PM
a = Invalid Date
b = Invalid Date
Does anyone know why this might be happening? It's got me stumped.
Date.parse uses RFC 2822 formatting and doesn't allow to specify a custom format. Though, if your input is consistently in the DD/MM/YYYY h:m:s AM/PM format, then you can use split to do the parsing yourself and manually create a Date object.
parseDate(a.cells[2].innerHTML);
parseDate(b.cells[2].innerHTML);
function parseDate(str) {
// Split into date, time, and AM/PM
var parts = str.split(" ");
// Split and parse the day, month, and year
var date = parts[0].split("/");
var day = parseInt(date[0]);
var month = parseInt(date[1]) - 1;
var year = parseInt(date[2]);
// Split and parse the hours, minutes, and seconds
var time = parts[1].split(":");
var hour = parseInt(time[0]);
var minute = parseInt(time[1]);
var second = parseInt(time[2]);
// Add 12 hours to the time if it's in the afternoon
if (parts[2] == "PM") { hour += 12; }
// Build and return our Date object
return new Date(year, month, day, hour, minute, second);
}
As others have mentioned, you can also use Moment to make things easier.
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 9 years ago.
I have two dates :
date1 = "2013-07-08 12:30:00"
date2 = "2013-07-08 13:30:00"
Now in javascript i want to match these two dates and its they dont match than i want to delete the appointment and if they match than nothing to do.
I tried this code but its not working :
if(date1 == date2)// Event already exists
{
// do nothing
}
else
{
// delete the record.
}
I tried to compare with "new Date(date1) == new Date(date2)" also but its not working either.
There is some problem in my code or date format. can anyone know how to do this and where i am wrong in this code ?
Thanks in advance.
Two different objects are never the same, you have to compare the numbers that make up the unix timestamp:
var date1 = "2013-07-08 12:30:00",
date2 = "2013-07-08 13:30:00";
var d1 = new Date(date1);
var d2 = new Date(date2);
if (d1.getTime() == d2.getTime()) {
}
FIDDLE
it works for me:
var date1 = "2013-07-08 12:30:00";
var date2 = "2013-07-08 12:30:00";
var date3 = "2013-07-08 12:00:00";
console.log(date1 == date2); //true
console.log(date1 == date3); //false
Jsfiddle link
Adeno has a valid answer but will fail if the dates are milliseconds appart (not the case in OP's example if you use a valid date string). To be sure you're comparing dates by minutes or days you can do:
function sameTime(dt1,dt2){
//round the dates to the minutes
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setSeconds(0,0);
t2.setSeconds(0,0);
return t1.toString()===t2.toString();
}
function sameDay(dt1,dt2){
//round the dates to the day
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setHours(0,0,0,0);
t2.setHours(0,0,0,0);
return t1.toString()===t2.toString();
}
function sameMonth(dt1,dt2){
//round the dates to the month
var t1=new Date(dt1);
var t2=new Date(dt2);
t1.setHours(0,0,0,0);
t2.setHours(0,0,0,0);
t1.setDate(1);
t2.setDate(1);
return t1.toString()===t2.toString();
}
var date1 = "2013-07-08T12:30:00",
date2 = "2013-07-08T13:30:00";
var d1 = new Date(date1);
var d2 = new Date(date2);
console.log(sameTime(d1,d2));//precise to the minute
console.log(sameDay(d1,d2));//precise to the day
console.log(sameMonth(d1,d2));//precise to the month
I am trying to compare two dates which are in Finnish time form like this: dd.mm.YYYY or d.m.YYYY or dd.m.YYYY or d.mm.YYYY.
I am having a hard time finding out how to do this, my current code won't work.
<script src="inc/date-fi-FI.js" type="text/javascript"></script>
<script type="text/javascript">
function parseDate() {
var date = $('#date').val();
var parsedDate = Date.parse(date);
alert('Parsed date: '+parsedDate);
}
function jämförMedIdag (datum) {
if (datum == null || datum == "") {
alert('Inget datum!');
return;
}
/*resultat = Date.compare(Datum1,Datum2);
alert(resultat); */
var datum = Date.parse(datum);
var dagar = datum.getDate();
var månader = datum.getMonth();
var år = datum.getYear();
var nyttDatum = new Date();
nyttDatum.setFullYear(år,månader,dagar);
var idag = new Date();
if(nyttDatum>idag) {
var svar = nyttDatum - idag;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
} else {
var svar = idag - nyttDatum;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
}
}
</script>
This code will try to calculate the difference between two dates, one of them being today. No success lolz.
Thanks in advance!
My final code (thanks RobG!):
function dateDiff(a,b,format) {
var milliseconds = toDate(a) - toDate(b);
var days = milliseconds / 86400000;
var hours = milliseconds / 3600000;
var weeks = milliseconds / 604800000;
var months = milliseconds / 2628000000;
var years = milliseconds / 31557600000;
if (format == "h") {
return Math.round(hours);
}
if (format == "d") {
return Math.round(days);
}
if (format == "w") {
return Math.round(weeks);
}
if (format == "m") {
return Math.round(months);
}
if (format == "y") {
return Math.round(years);
}
}
It is not fully accurate, but very close. I ended up adding some addons to it to calculate in day week month year or hour, anyone can freely copy and use this code.
If you are using Datejs, and the optional time.js module, you can run your calculations with the following code by creating a TimeSpan object:
Example
// dd.mm.YYYY or d.m.YYYY
// dd.m.YYYY or d.mm.YYYY
var start = Date.parse("20.09.2011");
var end = Date.parse("28.09.2011");
var span = new TimeSpan(end - start);
span.days; // 8
Of course the above could be simplified down to one line if you really want to be extra terse.
Example
new TimeSpan(Date.parse(end) - Date.parse(start)).days; // pass 'end' and 'start' as strings
Hope this helps.
If your dates are strings in the common form d/m/y or some variation thereof, you can use:
function toDate(s) {
var s = s.split('/');
return new Date(s[2], --s[1], s[0]);
}
You may want to validate the input, or not, depending on how confident you are in the consistency of the supplied data.
Edit to answer comments
To permit different separators (e.g. period (.) or hyphen (-)), the regular expression to split on can be:
var s = s.split(/[/\.-]/);
The date will be split into date, month and year numbers respectively. The parts are passed to the Date constructor to create a local date object for that date. Since javascript months are zero indexed (January is 0, February is 1 and so on) the month number must be reduced by one, hence --s[1].
/Edit
To compare two date objects (i.e get the difference in milliseconds) simply subtract one from the other. If you want the result in days, then divide by the number of milliseconds in a day and round (to allow for any minor differences caused by daylight saving).
So if you want to see how many days are between today and a date, use:
function diffToToday(s) {
var today = new Date();
today.setHours(0,0,0);
return Math.round((toDate(s) - today) / 8.64e7);
}
alert(diffToToday('2/8/2011')); // -1
alert(diffToToday('2/8/2012')); // 365
PS. The "Finnish" data format is the one used by the vast majority of the world that don't use ISO format dates.
Using the Date object:
var today = Date.today();
var dateToday = Date.parse(today.toString('MMMM d, yyyy'));
var prevMonthDate = dateToday.addDays(-30);
var difference = (dateToday - prevMonthDate)/86400000;
console.log(difference); //will give you the difference in days.