String dates comparison in javascript - javascript

So, I have two variables and one function:
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
const dateToCompare=moment.utc(endDate).format('DD-MM-YYYY')
const maximum=moment.utc(addDays(new Date(),14)).format('DD-MM-YYYY')
However, I do not know how to compare them, since they are now formatted as strings, but at the same time new Date(dateToCompare) doesn't work.
Can someone give me a hint?

Why are you using built–in methods to add days when you are using moment.js? Consider:
let maximum = moment.utc().add('day',14).format('DD-MM-YYYY')
To set a date to the start of a day, use the moment.js startOf method:
let maximum = moment.utc().add('day',14).startOf('day')
let dateToCompare = moment.utc(endDate).startOf('day')
You can compare the dates as strings if formatted as YYYY-MM-DD, or just leave them as moment objects and compare those using isSame, isAfter, isSameOrBefore, etc.
When parsing strings as in:
const dateToCompare=moment.utc(endDate)
you should always pass the format to parse unless endDate is a Date or moment object. new Date(dateToCompare) doesn't work because Why does Date.parse give incorrect results?

If what you're trying to do is strip out the time and just compare the dates, don't do a string conversion; just set the hour, minutes, and seconds on your Date objects to zero before making your date comparison.
let foo = new Date();
console.log(foo);// date includes time
foo.setHours(0); foo.setMinutes(0); foo.setSeconds(0);
console.log(foo) // date set to midnight (in your timezone)

Related

Create JavaScript Date object from date string + time string + timezone offset string

I have total 4 different input i.e.:
Date string (2020-05-05)
Time string (15:30)
Timezone offset (-09:00)
I want to combine these strings into one datetime object like (2020-05-05T15:30:00-09:00) no-matter what my local browser timezone is. The issue is when I combine these strings and I try to make date object using new Date() function, my datetime gets converted into UTC timestamp.
I tried this:
const date =
moment(this.actualDateOfSurgeryDate).format(YYYYMMDD) +
'T' +
moment(this.actualDateOfSurgeryTimeDropDown + ' ' + this.actualDateOfSurgeryTimeAM_PMDropDown, ['h:mm A']).format('HH:mm:ss') +
offsetTime;
this.caseDetail.actualDateOfSurgery = new Date(date);
This gives me output something like: 2020-05-05T04:30:00.000Z
How can I get my desired output: 2020-05-05T15:30:00-09:00 ??
I have moment js available in my project
I want to combine these strings into one datetime object like (2020-05-05T15:30:00-09:00)
Date objects are extremely simple, they're just a time value that is an offset in milliseconds since 1970-01-01T00:00:00Z, so are inherently UTC. The built–in parser is unreliable and lacks any functionality such as format tokens.
So if you have separate values like:
Date string (2020-05-05)
Time string (15:30)
Timezone offset (-09:00)
then you can create a string that is compliant with the format defined in ECMA-262 and that should be parsed correctly by the built–in parser, e.g.
new Date('2020-05-05T15:30:00.000-09:00')
However, general advice is to avoid the built–in parser due to differences in implementations. Also, the format must be exact (e.g. including seconds and milliseconds in the timestamp, colon (:) in the offset) or some implementations will reject it as malformed and return an invalid date.
Once you have a Date object, getting a "local" timestamp with offset is an issue of formatting, which has been answered many times before (e.g. How to format a JavaScript date). There aren't any decent built–in formatting functions (toLocaleString with options is OK for some purposes but generally lacking in functionality), so you'll have to either write your own function, or use a library.
The following examples use Luxon, which is suggested as the upgrade path from moment.js.
With Luxon, if you specify a representative location, you'll get the offset for that location at the date's date and time. Alternatively, you can fix the offset to a set value, essentially setting it for a timezone without a representative location, so it doesn't have any reference to daylight saving or historic offset changes:
let DateTime = luxon.DateTime;
// Offset per the specified location
let d0 = DateTime.fromISO('2020-01-01', {zone: 'America/Yakutat'});
let d1 = DateTime.fromISO('2020-06-30', {zone: 'America/Yakutat'});
console.log(d0.toString());
console.log(d1.toString());
// Fixed offset per the supplied string
let d2 = DateTime.fromISO('2020-05-05T15:30:00.000-09:00', { setZone: true});
let d3 = DateTime.fromISO('2020-01-01T15:30:00.000-09:00', { setZone: true});
console.log(d2.toString());
console.log(d3.toString());
<script src="https://cdn.jsdelivr.net/npm/luxon#1.24.1/build/global/luxon.min.js"></script>
I get 16:30 due to DST
A date before March or after October will give 15:30
let dateString = "2020-05-05"+"T"+"15:30"+":00"+"-09:00"
console.log(dateString)
const date = new Date(dateString)
console.log(date)
const Anchorage = date.toLocaleString('en-US', {timeZone: 'America/Anchorage', hour12: false})
console.log(Anchorage)
let options = {}
options.timeZone = 'America/Anchorage';
options.timeZoneName = 'short';
console.log(date.toLocaleDateString('en-US'), date.toLocaleTimeString('en-US', options));

setDate() is using current date as basis instead of desired object

I'm trying to add days to a Date object, but the output is not as desired:
// THIS IS JUST A SIMPLIFIED EXAMPLE.
let date = new Date("2019-01-01 00:00:00")
let finalDate = new Date()
finalDate.setDate(date.getDate() + 10)
console.log(finalDate)
Desired output:
11/01/2019 00:00:00
Actual output:
31/08/2019 13:06:30
It's using the current system date as a base and setting it to finalDate. which is not what I'm looking for.
The way you were declaring your literal date was in error. Also, you're better passing the existing date as a parameter to the constructor for the second one.
let date = new Date("2019-01-01 00:00:00");
let finalDate = new Date(date);
finalDate.setDate(date.getDate() + 10);
console.log(finalDate)
If your desired output is 11/01/2019 then you need to change a few things in how you're calculating your dates.
Here's code that get you what you're looking for:
let date = new Date('2019/01/01 00:00:00');
let finalDate = date;
finalDate.setMonth(date.getMonth() + 10);
console.log(finalDate);
Notice that for finalDate, I'm not setting it to a new instance of a date, but rather assigning it the value of the date variable. This way the two are the exact same date and allows us to begin adding months to the one we wish to add months to. Otherwise the days may not come out the same by initializing finalDate as its own separate date object.
Also notice that I'm calling getMonth rather than getDate, since we're adding months strictly.
Here is a working jsfiddle of your desired results:
https://jsfiddle.net/yzmk61xf/#&togetherjs=sSETlrppq6

How do I get difference between two dates of unknown format in javascript?

I get a date as String from server like this: 2017-01-23T16:08:45.742Z. I want to find the difference in days, between this and the current date (or precisely, current time). I could just extract date alone (without time) and check, but I'd need a precise answer based on provided time & current time.
How do I achieve this?
Should be easy....
var dateFromServer = '2017-01-23T16:08:45.742Z'
var msInDay = 1000 * 60 * 60 * 24
var difference = (new Date(dateFromServer) - Date.now()) / msInDay
document.write('difference = ' + difference + ' days')
That date format looks like ISO_8061. https://en.wikipedia.org/wiki/ISO_8601
Use the Date object to get the difference between today and the other date in milliseconds, then divide by the number of milliseconds in a day.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
The code below can be condensed into a single line but I wanted to be explicit.
let date = "2017-01-23T16:08:45.742Z";
let d1 = new Date(date); // given date
let today = new Date(); // today's date
let diff = (d1 - today); // difference in milliseconds
let days = diff / 8.64e+7; // divide difference by 1 day in milliseconds
console.log(days)
Point of clarification: if I understand you correctly, you're actually trying to get the difference between two dates of different formats, not two dates of unknown formats. That's way easier.
Further, it looks like your server string is already stored in ISO format, which again makes this way easier.
I'd recommend looking at the JavaScript Date object. I believe in this case your best bet would be something like this:
// Your string from the server
var data_from_server = '2017-01-23T16:08:45.742Z';
// Create a new Date() object using the ISO string provided by your server
var olddate = new Date(data_from_server);
// Create a new empty Date() object, which should default to the current time
var currentdate = new Date();
// Subtract the two
var dif = currentdate.getTime() - olddate.getTime();
// Alert the result
alert(dif);

Compare different time zone date in Jquery

How to compare dates from different time zone?
for e.g.
x = "2013-12-02T10:10:17-0400" // (timezone EST)
and compare this date to current date
var d = new Date(); // timezone(PST)
check x < d ?
When it comes to dealing with dates and times in JavaScript, I usually use Moment.js which is a library exactly for this purpose.
Its URL is http://momentjs.com/
Then you can simply parse the given string with this line:
// Parse the given datetime
var mydate = moment("2013-12-02T10:10:17-0400");
And you can also compare two different moment values:
// Compare given datetime with the current datetime
if (moment("2013-12-02T10:10:17-0400") > moment()) {
// ...
}
Or you can just convert it to a regular JavaScript Date object:
// Parse given datetime and convert to Date object
var mydate = moment("2013-12-02T10:10:17-0400").toDate();
// Compare to current datetime
if (mydate > (new Date())) {
// ...
}
Note that the unary + operator also works with moment objects just as you would expect. So +moment() outputs the same as +(new Date()).
It's also very well documented, the Moment.js docs page has a ton of examples and useful info about it.
Better convert any of the dates to a common timezone(better to have UTC)
Now convert the datetime to milliseconds
Compare the milliseconds
Hope you understand
Use this javascript library to manipulate dates in different time zones: https://github.com/mde/timezone-js
It uses the TZ database: http://en.wikipedia.org/wiki/Tz_database

How to create object of Date("23.03.2010")

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.

Categories