Convert String Day and Date to Date in Javascript [duplicate] - javascript

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Compare two dates with JavaScript
(44 answers)
Closed 5 years ago.
I have a date format:
Thursday, 10 Aug 2017
I have an array of dates like this above. I have to find out the earliest date in the the array in javascript.
How can I effectively parse the date in the above format to check which is the earliest date.
How can I do that?
I also tried Date.parse method. Its working. Is it a good way of doing this? Can this method break or throw some exceptions? Also will this add any added latency to the code? As this method checking is alll done client side and we don't want any latency of any kind.
Any leads appreciated.

You can use momentjs and parse the date with
moment.lang("en-au").format('LLLL');
Have a look at moment
If you do not want moment just use what you say above
var d = new Date('Thursday, 10 Aug 2017')
d.getDate() --- 10
d.getFullYear() --- 2017
And if you want to find the earliest one, you can do the following(it does need refactor):
var earliest = null;
var dates = ['Thursday, 11 Aug 2017', 'Thursday, 10 Aug 2017' , 'Thursday, 15 Aug 2017'];
dates.forEach(date => {earliest = earliest == null ? new Date(date) : (new Date(date).getTime() < earliest.getTime()) ? new Date(date) : earliest});

This is a duplicate, but you've asked many questions in one go:
How can I effectively parse the date in the above format to check which is the earliest date. How can I do that?
Duplicate of Why does Date.parse give incorrect results?
I also tried Date.parse method. Its working. Is it a good way of doing this?
No, for the reasons outlined in the duplicate: it gives unreliable results.
Can this method break or throw some exceptions?
No, but it gives unreliable results.
Also will this add any added latency to the code?
No, but it gives unreliable results.

Related

Validate if string is a date [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
How to validate a date?
(11 answers)
Closed 2 years ago.
I've seen many articles about this but not quite found what I am looking for yet.
I'm trying to simply check if a string is a date. That string might contains a number such as 2012 though.
var timestamp = Date.parse('foo 2012');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
console.log('DATE', d)
}else{
console.log('TEXT');
}
//OUTPUT: DATE Sun Jan 01 2012 00:00:00 GMT+1100 (Australian Eastern Daylight Time)
Why does javascript convert foo 2012 into a date when it's clearly not?
How can I validate that my string is an actual date ?
A string is never a date.
A string can represent a date. There are many ways to represent the same date through different string formats.
This means "validating that a string is a date" is an impossible task. What you can do instead is:
Validate that the format of the string conforms to some well-known format and that its contents are valid.
Try to parse a given string as an expected format and either throw an error or return a "guard" value to indicate that the parsing was not a success.
JavaScript took a third option, which is like option 2, only it returns a value indicating its "best efforts" at working with the garbage input. That's apparently why it saw a year in your string and decided "well, I guess I can make a date with this?" As #Pointy pointed out, it's actually in the spec that if the JavaScript string doesn't match one of the two supported formats, the implementer can decide what the result should be.
I'd highly recommend that if you're dealing with date strings, you should stick with a consistent format. I'm a big fan of ISO 8601 date/time strings because they are time zone aware, easy to sort, and are widely supported (including being easily parsed by JavaScript). If you're requiring the strings are in a standard format, it's easier to do things like finding A RegExp that can validate the input.

Javascript Subtract/Add 1 month from date [duplicate]

This question already has answers here:
JavaScript function to add X months to a date
(24 answers)
Adding months to a Date in JavaScript [duplicate]
(2 answers)
Closed 2 years ago.
I'm trying to find a method that reliably subtracts 1 month from a javascript date object.
I have this code:
var shippedDate = new Date('12/31/2020');
var tempDate = new Date(shippedDate.setMonth(shippedDate.getMonth() - 1)); //subtract 1 month
alert(tempDate);
The value in tempDate after this code runs is 12/1/2020 when it should actually be 11/30/2020.
I checked my math with this online date calculator: https://www.timeanddate.com/date/dateadded.html?m1=12&d1=31&y1=2020&type=sub&ay=&am=1&aw=&ad=&rec=
Thanks.
December has 31 days so when you subtract 1 month, you get 31 November which doesn't exist, so it rolls over to 1 December.
You can test the date (day in month) to see if it's the same, and if not, set the date to 0 so it goes to the last day of the previous month.
Also, setDate modifies the Date object so no need to create a new one:
function subtractMonth(date, months) {
let d = date.getDate();
date.setMonth(date.getMonth() - months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
let d = new Date(2020, 11, 31); // 31 Dec 2020
console.log(subtractMonth(d, 1).toString()); // 30 Nov 2020
This has side effects so that sequentially subtracting 2 months may give a different result to subtracting 2 months in one go.
Also in regard to new Date('12/31/2020'), see see Why does Date.parse give incorrect results?
PS
I answered this before I remembered that there were plenty of questions about adding months that also cover subtracting. So I marked this question as a duplicate and rather than delete this answer, left it for posterity.
If you wish to vote for an answer, please go to one of the duplicates and vote for an answer there. :-)
On my own experience, I may qualify all around Date calculation in javascript as completely unbearable pain.
Avoid as possible own crafted function to any Date manipulation. There are too many traits to lose mind at all. Timezones, wrong clocks, timezone on your own host vs. timezone on server, unexpected toString conversion according to local host timezone/clock.
If you rally need to make some dates calculation use battle tested library, like date-fns, moment.js, etc.
By the way your example almost correct, you just have chosen not suitable time to try to test it. The only one that I see problematic it's using setMonth that mutate original shippedDate.

Convert Date to javascript format [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Parsing a string to a date in JavaScript
(35 answers)
Closed 2 years ago.
I am trying to convert this date into Mon Nov 26 2018 10:32:04 GMT (I am getting this data from the Api so i can't make changes to it)
I assume it is considering 26 as months thats why it is showing it as invalid date
Can Anyone help me with this. How to convert that date into the expected output i specified.
How to get
var d = new Date("26-11-2018 10:32:04")
return d; //Error: Invalid Date
expected Output: Mon Nov 26 2018 10:32:04 (IST)
Use moment.js to parse the date.
moment("26-11-2018 10:32:04", "DD-MM-YYYY HH-mm-ss").toDate()
Alternatively, if you really don't want to use moment for whatever reason, you can use regex magic.
new Date("26-11-2018 10:32:04".replace(/^(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)$/, "$3-$2-$1T$4:$5:$6Z"))
This is not a robust as #Yevgen answer but it also much simpler.
All I'm doing is removing the - and flipping the day and month values
const items = "26-11-2018 10:32:04".split('-')
new Date(`${items[1]} ${items[0]} ${items[2]}`)
This works for personal projects but I highly recommend using moment.js

How to convert utc to string in momentjs?

I want to use moment for this.
moment("date","YYYYMMDD").fromNow(); // ~~ years ago example
I get UTC from MongoDB createAt. but I don't know convert UTC to string (variable date).
ex) mongodb_createAt = 2018-09-18T12:22:19.491Z
this mongodb_createAt convert to string(date)
I want to utc convert to date string..
I want to display ~~ years ago (like youtube)
How to ??
thanks.
Look at moment documentation https://momentjs.com/docs/#/displaying/fromnow/
Try moment().fromNow(); it should output ... years ago
You could use momentjs's .humanize() method to achieve this.
First, you'll need to calculate the duration between your timestamp 2018-09-18T12:22:19.491Z and the current time. Once you have this duration, you can then make use of .humanize() like so:
var mongodb_createAt = '2018-09-18T12:22:19.491Z';
var millisecondsElapsed = moment(mongodb_createAt).diff(moment());
var displayString = moment.duration(millisecondsElapsed).humanize(true);
console.log(displayString) // eg 17 hours ago
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Note that the true argument passed to .humanize(true) adds the tense to the displayString string - ie true causes a result like "17 hours ago" rather than just "17 hours"
For more information on the humanize() method, see the official documentation

Incorrect date being set with new Date() [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
When using the below line I am expecting the result to be '22/09/2017 14:05:43', however it is actually returning '09‎/‎10‎/‎2018‎ ‎14‎:‎05‎:‎43'.
var theDate = new Date('22/09/2017 14:05:43').toLocaleString();
I know there are js libraries out there such as moment.js that can be used for a lot of date time manipulation, but I was just wondering if anyone knew why this was happening and how I can get this to return the expected date?
Parsing of date strings is mostly implementation dependent, so it's generally recommended to avoid the built-in parser. Most browsers treat JavaScript dates with a pattern xx/xx/xxxx as MM/DD/YYYY, so 22/09/2017 is seen as either an invalid date (e.g. Safari, Firefox, Chrome), or the 9th day of the 22nd month of 2017 (apparently your browser).
Your browser is interpreting it as 'the 9th day of the 22nd month', so you're ending up on October 9th 2018, 22 months and 9 days into 2017.
To resolve this, you can separate the string into parts and give them to the constructor, avoiding the built-in parser (remembering to subtract 1 from the month number):
new Date(2017, 8, 22, ...)
Refer to MDN's Date documentation for more information.
Well the initial date string you passed to the Date constructor is wrong, it should be in the format 'MM/DD/YYYY HH:mm:ss'.
Your actual code will give Invalid Date:
var theDate = new Date('22/09/2017 14:05:43');
console.log(theDate);
var str = theDate.toLocaleString();
console.log(str);
Here 22 will be treated as a month and 09 will be treated as day. You need to fix it so it follows the Date standards:
var theDate = new Date('09/22/2017 14:05:43');
console.log(theDate);
var str = theDate.toLocaleString();
console.log(str);

Categories

Resources