Convert specific date in Javascript [duplicate] - javascript

This question already has answers here:
Parse DateTime string in JavaScript
(9 answers)
Closed 5 years ago.
I have problem with convert date which I get from API. Format is for example "16/09/25"
I try do it like this
var x = new Date(dateFromApi)
and console thorw me error.

Parsing a date string is very simple. A function that will work in any host from IE 4 onward is:
function parseDMY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[1]-1, b[0]);
}
console.log(parseDMY('16/09/25'));
Where the year is >= 0 or <= 99, 1900 is added so 25 becomes 1925. Preserving years in this range (so 25 is 0025) requires an additional line of code.

It is safest to provide the Date constructor with the individual parts of the date (i.e., year, month and day of the month).
In ES6 you can provide those elements like this:
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
The map is needed to subtract one from the month number, as it should be zero-based in numeric format.
Note the new Date(year, month, day) version of the constructor will assume 19xx when you provide only 2 digits.
var dateFromApi = "16/09/25"
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
console.log(x.toDateString());
In ES5, it would be a bit longer, like this:
new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
var dateFromApi = "16/09/25"
var x = new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
console.log(x.toDateString());
Of course, this assumes that the input format is consistently in the order DD/MM/YY (or D/MM/YYYY, as long as the order is the same); that valid dates are passed, and that you accept how 2-digit years are mapped to 4-digit years.

Your format is DD/MM/YY and it is not accepted by Date and will throw an error.
This is because, as mentioned by #MattJohnson, the accepted Date formats vary by locale and the only official format is YYYY-MM-DD (which is derived from ISO date string. Read here).
In most cases, Date will accept the format YY-MM-DD. So we can simply do this:
var date = "16/09/25"; // date received from API
var split_date = date.split('/'); // outputs ["16","09",""25"]
var rearranged_date = [split_date[1], split_date[0], split_date[2]].join('/'); // outputs "09/16/25"
var proper_date = new Date(rearranged_date);
In other cases, it is best to provide the full-year YYYY instead of just YY.

Related

Create Date object passing a date format of mmddyyyy [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 10 months ago.
I'm trying to create a date with the format 'mmddyyyy'. I've noticed I can pass a four digit string, but when I use the format above, it says invalid date. How can I go about this with pure js?
let dateString = '01012022'
let d = new Date(dateString)
maybe you want something like that
let dateString = '01012022'
let [match, dd, mm, yyyy] = dateString.match(/(\d{2})(\d{2})(\d{4})/)
// iso format
let d = new Date(`${yyyy}${mm}${dd}`)
Seems like you have to split your string into pieces then use common Date() constructor with separated day, month and year
//Your string with date
let dateString = '01012022';
//extracting 2 first numbers as m (month), 2 second as d (day) and the last 4 as y (year)
let {d,m,y} = /(?<m>\d{2})(?<d>\d{2})(?<y>\d{4})/.exec(dateString).groups;
//then create new date using constructor
let date = new Date(y,m,d);

Is there a built in way to get date in 6 digit format YYMMDD? [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I'm trying to create a function the will create a list of dates formatted in a 6 digit number starting from today till August of 2018. the result should be something like this:
[190322, 190321, 190320, ...]
I'm not sure if there is a built is a way to get the date in this 6 digit format?
Assisted by Date objects, you could proceed like this:
function getDateNumsBetween(a, b) {
// b should come before a
a = new Date(a); // new instance to avoid side effects.
const result = [];
while (a >= b) {
result.push(((a.getFullYear()%100)*100 + a.getMonth()+1)*100 + a.getDate());
a.setDate(a.getDate()-1);
}
return result;
}
const result = getDateNumsBetween(new Date(), new Date("August 1, 2018"));
console.log(result);
There is no build in "one function do it all" to get your outcome right away.
Option 1:
However you can use the provided functions getFullYear, getMonth and getDate to get to your result:
let d = new Date()
let formatted = d.getFullYear().toString().slice(2,4) +
(d.getMonth()+1 > 10 ? d.getMonth()+1 : `0${d.getMonth()+1}`) +
(d.getDate() > 10 ? d.getDate() : `0${d.getDate()}`)-0
Lets get through it line by line
// Uses the getFullYear function which will return 2019, ...
d.getFullYear().toString().slice(2,4) // "19"
// getMonth returns 0-11 so we have to add one month,
// since you want the leading zero we need to also
// check for the length before adding it to the string
(d.getMonth()+1 < 10 ? d.getMonth()+1 : `0${d.getMonth()+1}`) // "03"
// uses getDate as it returns the date number; getDay would
// result in a the index of the weekday
(d.getDate() < 10 ? d.getDate() : `0${d.getDate()}`) // "22"
// will magically convert the string "190322" into an integer 190322
-0
Might be worth saying that this is a quick "how to achieve" it without installing any npm package but make sure to cover edge cases yourself as there are many when it comes to dates.
Option 2:
Another option would be to go for the toISOString and use split, a bit of regex, and slice to receive your outcome:
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8)-0
Again step by step with the output:
d.toISOString() // "2019-03-22T22:13:12.975Z"
d.toISOString().split('T') // (2) ["2019-03-22", "22:13:12.975Z"]
d.toISOString().split('T')[0] // "2019-03-22"
d.toISOString().split('T')[0].replace(/\-/g, '') // "20190322"
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8) // "190322"
d.toISOString().split('T')[0].replace(/\-/g, '').slice(2,8)-0 // 190322

Check different date formats

I have function:
sample(date){
//operations, for example add one week (7 days)
return date;
}
var one = new Date('2012-07-16');
var two = new Date('07/16/2012');
var new = sample(one); // or sample(two)
var day = new.getDate();
var month = new.getMonth();
var year = new.gerYear();
alert(day + month + year);
and now i would like show this date, but how can i check format this date?
For example:
alert(sample(one));
should show me date with format 2012-07-23
and if
alert(sample(one));
should show me 07/23/2012
but how can i check format current date? is this possible?
Date objects don't "remember" the format with which they were created - they're just a wrapper for the standard Javascript "milliseconds since the epoch" time values.
You'll need to either roll your own "date to string" functions, or use one of the popular existing libraries (e.g. Datejs)

Compare dates javascript

I need to validate different date's with some javascript(jquery).
I have a textbox with, the inputmask from jquery (http://plugins.jquery.com/plugin-tags/inputmask). The mask that i use is "d/m/y".
Now i have set up a CustomValidator function to validate the date.
I need 2 functions. One to check if the given date is greater then 18 years ago. You must be older then 18 year.
One function to check if the date is not in the future. It can only in the past.
The function are like
function OlderThen18(source, args) {
}
function DateInThePast(source, args) {
}
As you know the value you get back with args.Value is 27/12/1987 .
But how can i check this date in the functions? So that i can set args.IsValid to True or False.
I tried to parse the string(27/12/1987) that i get back from the masked textbox to a date but i get always a value back like 27/12/1988.
So how could I check the given dates with the other dates?
The simple way is to add 18 years to the supplied date and see if the result is today or earlier, e.g.:
// Input date as d/m/y or date object
// Return true/false if d is 18 years or more ago
function isOver18(d) {
var t;
var now = new Date();
// Set hours, mins, secs to zero
now.setHours(0,0,0);
// Deal with string input
if (typeof d == 'string') {
t = d.split('/');
d = new Date(t[2] + '/' + t[1] + '/' + t[0]);
}
// Add 18 years to date, check if on or before today
if (d.setYear && d.getFullYear) {
d.setYear(d.getFullYear() + 18);
}
return d <= now;
}
// For 27/4/2011
isOver18('27/4/2011'); // true
isOver18('26/4/2011'); // true
isOver18('28/4/2011'); // false
try this to start:
var d = new Date(myDate);
var now = new Date();
if ((now.getFullYear() - d.getFullYear()) < 18) {
//do stuff
}
The javascript date object is quite flexible and can handle many date strings.
You can compare two Date objects or use the Date interface methods, such as getSeconds() of getFullYear() in order to deduce useful data regarding the date.
See Date object reference formore details.
You'll need to construct, modify and compare Date objects - something like this:
// str should already be in dd/mm/yyyy format
function parseDate(str) {
var a = str.split('/');
return new Date(parseInt(a[2], 10), // year
parseInt(a[1], 10) - 1, // month, should be 0-11
parseInt(a[0], 10)); // day
}
// returns a date object for today (at midnight)
function today() {
var date = new Date();
date.setHours(0, 0, 0);
return date;
}
function DateInThePast(str) {
// date objects can be compared like numbers
// for equality (==) you'll need to compare the value of date.getTime()
return parseDate(str) < today();
}
function OlderThan18(str) {
// left as an exercise for the reader :-)
}

Validate two dates of this "dd-MMM-yyyy" format in javascript

I have two dates 18-Aug-2010 and 19-Aug-2010 of this format. How to find whether which date is greater?
You will need to create a custom parsing function to handle the format you want, and get date objects to compare, for example:
function customParse(str) {
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;
while(n--) { months[months[n]]=n; } // map month names to their index :)
matches = str.match(re); // extract date parts from string
return new Date(matches[3], months[matches[2]], matches[1]);
}
customParse("18-Aug-2010");
// "Wed Aug 18 2010 00:00:00"
customParse("19-Aug-2010") > customParse("18-Aug-2010");
// true
You can do the parsing manually, for your given format, but I'd suggest you use the date.js library to parse the dates to Date objects and then compare.
Check it out, its awesome!
And moreover, its a great addition to your js utility toolbox.
The native Date can parse "MMM+ dd yyyy", which gives:
function parseDMY(s){
return new Date(s.replace(/^(\d+)\W+(\w+)\W+/, '$2 $1 '));
}
+parseDMY('19-August-2010') == +new Date(2010, 7, 19) // true
parseDMY('18-Aug-2010') < parseDMY('19-Aug-2010') // true
Firstly, the 'dd-MMM-yyyy' format isn't an accepted input format of the Date constructor (it returns an "invalid date" object) so we need to parse this ourselves. Let's write a function to return a Date object from a string in this format.
function parseMyDate(s) {
var m = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
var match = s.match(/(\d+)-([^.]+)-(\d+)/);
var date = match[1];
var monthText = match[2];
var year = match[3];
var month = m.indexOf(monthText.toLowerCase());
return new Date(year, month, date);
}
Date objects implicitly typecast to a number (milliseconds since 1970; epoch time) so you can compare using normal comparison operators:
if (parseMyDate(date1) > parseMyDate(date2)) ...
Update: IE10, FX30 (and likely more) will understand "18 Aug 2010" without the dashes - Chrome handles either
so Date.parse("18-Aug-2010".replace("/-/g," ")) works in these browsers (and more)
Live Demo
Hence
function compareDates(str1,str2) {
var d1 = Date.parse(str1.replace("/-/g," ")),
d2 = Date.parse(str2.replace("/-/g," "));
return d1<d2;
}

Categories

Resources