Regular expression to fetch year from date - Javascript - javascript

Can somebody please help me construct a regular expression in Javascript to check if year 2017 exists or a year starting with 19 or 20 (century) exists in a given date.
My date format is : Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time).
I tried this but it fails:
var str = "Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt = new RegExp("/^\S{3}[\s]\S{3}[\s]\d{2}[\s]\d{4}$/");
var res = patt.test(str);
Thanks,
Haseena

You can use Date.getFullYear() method.
var d = new Date("Fri Dec 01 1999 00:00:00 GMT-0800 (Pacific Standard Time)");
var year = d.getFullYear();

Here is example you can use.
var str="Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt=/(\w{3}\s){2}\d{2}\s(\d{4})\s(.*)/;
var results = patt.exec(str);
console.log(results);
console.log(results[2]);
The second group is match the year.

The year validation with multiple condition is not quite a regex thingy
If I have understood your question then you can try this:
^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*
It will only match if the year is 2017
It will match if the year starts with 19
It will match if the year starts with 20
If match is found, then the year can be found in group 1
Explanation
const regex = /^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*$/gm;
const str = `Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)`;
let m;
if((m = regex.exec(str)) !== null) {
console.log("Full match ="+m[0]);
console.log("Matched year ="+m[1]);
}
else
console.log("no match found");

With a fixed date format, this is really easy:
First, just extract your year using a regular expression var year = str.match(/^.{11}(\d{4})/)[1]
.match returns an array where the first element is the entire matched string and subsequent elements are the parts captured in parentheses.
After you have this, you can test if year === '2017' or if year.substr(0, 2) === '19'.
There are about a dozen other ways to do this, too.
var myDate = 'Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)';
function isCorrectYear(dateString) {
var year = dateString.match(/^.{11}(\d{4})/)[1];
if (year === '2017') return true;
}
if (isCorrectYear(myDate)) {
alert("It's the correct year.");
}
Something just occurred to me... "year 2017 exists or a year starting with 19 or 20". Doesn't that cover every year in every date string you are ever likely to encounter? I don't think they had Javascript before the 1900s and I doubt anything any of us will write will still be in use after the year 2100.

Related

Why do this dates not match?

i have this code which works with dates:
let startDate = new Date(toolOrder.jsAppStartDate.getTime()); // clone date
startDate.setDate(startDate.getDate() - Math.floor((days - 1) / 2)); // sub some days
console.log(toolOrder.jsAppStartDate); // Output: Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
console.log(toolOrder.jsAppStartDate.getTime()); // Output: 1695247200000
console.log("--------------");
for (let index = 0; index < days; index++)
{
console.log(startDate);
console.log(startDate.getTime());
// ... some drawing code here ...
startDate.setDate(startDate.getDate() + 1); // add one day
if(startDate === toolOrder.jsAppStartDate) // check if start date reached
{
console.log("Dates match");
startDate = new Date(toolOrder.jsAppEndDate.getTime());
}
}
The output of the log before the loop is:
Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
---------------
The output from the loop is:
Date Mon Sep 18 2023 00:00:00 GMT+0200 (Central European Summer Time)
1694988000000
Date Tue Sep 19 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695074400000
Date Wed Sep 20 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695160800000
Date Thu Sep 21 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695247200000
Date Fri Sep 22 2023 00:00:00 GMT+0200 (Central European Summer Time)
1695333600000
So even if the dates match in loop 3, the if condition is not true. It works when I use
if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())
but I thought it should work without also?
=== compares identity so:
startDate === toolOrder.jsAppStartDate
Means: is startDate the same object [in memory] as toolOrder.jsAppStartDate which is not the case because toolOrder.jsAppStartDate is a different object and not the object referred to by the name startDate.
mdn says this about the strict equality operator:
If both operands are objects, return true only if they refer to the same object.
(emphasis mine)
if(startDate.getTime() === toolOrder.jsAppStartDate.getTime())
Works because you're now comparing numbers instead of objects.
The rule for the two operands being numbers is:
Otherwise, compare the two operand's values:
Numbers must have the same numeric values. +0 and -0 are considered to be the same value.
mdn (emphasis mine)
You are comparing Date instances with each other when you're using the === operator. However, they are not the same instance. Each new Date creates a unique, new instance (unless the class constructor deliberately returns a previously created instance [for more info: singleton pattern]).
When you are comparing each instance's getTime() result, you are comparing 2 primitive values (numbers in this case). Primitive values are not class instances; so === works like == with primitives.

How to create function that return a Date object?

1 - Make a function that given a date in text format "dd/mm/yyyy" returns a Date object with that date, using the Split() method.
2 - You have to do a "console.log() of the Date object created" and it should output something similar to
Mon Dec 2 2019 11:36:25 GMT+0100 (Central European Standard Time).
I have tried this but I don't know why when I write a console.log
I get the following:
2022-12-05T00:00:00.000Z
And I try to get it to appear something like this:
Mon Dec 2 2019 12:30:05 GMT+0100 (Central European Standard Time)
function convertDate(date) {
let dateArray = date.split("/");
let DateString = dateArray[2] + "/" + dateArray[1] + "/" + dateArray[0] + "Z";
let dateDate = new Date(dateString);
return dateDate;
}
console.log(convertDate("05/12/2022"));
you can use new Date() to get the date like "Wed Dec 28 2022 11:36:25 GMT+0100"
let date = new Date("05/12/2022");
console.log(date);
output will be Thu May 12 2022 00:00:00 GMT+0500 (Pakistan Standard Time) {}

What type of date strings are these in JS?

I get a date string as Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time) from one place. I get it from 2021-09-17T11:50:59-04:00 in a second place.
I want to convert the first format to the second.
I am doing this in a crazy way, so I am thinking there must be a better one.
var d = new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`);
var iso = d.toISOString();
var time = d.toTimeString();
console.log(iso);
console.log(time);
var [date] = iso.split('T')
var [,localTime, timezone] = time.match(/([^ ]+) GMT([^ ]+)/);
var timezoneWithColon = timezone.replace(/(-*[0-9]{2,2})([0-9]{2,2})/,"$1:$2")
var desiredFormat = '2021-09-17T11:50:59-04:00';
var convertedFormat = `${date}T${localTime}${timezoneWithColon}`;
console.log(desiredFormat)
console.log(convertedFormat)
console.log(desiredFormat === convertedFormat);
The fiddle is over at https://jsfiddle.net/Dave_Stein/8tLv2g4j/.
2021-09-17T11:50:59-04:00 is an ISO-8601 date string.
toISOString should work, however it will convert the time to UTC. If you want this to format in your current timezone, you'll have to use a library such as date-fns:
import { formatISO } from 'date-fns'
formatISO(new Date(`Fri Sep 17 2021 11:50:59 GMT-0400 (Eastern Daylight Time)`))
// prints '2021-09-17T11:50:59-04:00'

JS UTC timestamp behaviour

I'm confused about how this time conversion works. I have timestamp 1462060800000 which when I turn in to date correctly becomes:
Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
but then when I want to get the month with const startMonth = start.getUTCMonth() I get 4 instead of 5. Why is this happening and what do I need to do to get the correct month?
const timestamp = 1462060800000
const start = new Date(timestamp)
console.log(start) // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
const startYear = start.getUTCFullYear()
const startMonth = start.getUTCMonth()
console.log(startMonth) // 4
getUTCMonth() returns zero-based months. 4 is correct. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth.
I get it it's actually a month index that starts with 0.
The getUTCMonth() returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year).
From the docs see Date.prototype.getUTCMonth()
The getUTCMonth() method, like getMonth(), has a zero (0) count. This means that the period will be like this - 0 and 11. To get the desired month, you need to add +1:
const startMonth = start.getUTCMonth() + 1;
Loot it.
const timestamp = 1462060800000;
const start = new Date(timestamp);
console.log(start); // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)
const startYear = start.getUTCFullYear();
const startMonth = start.getUTCMonth() + 1;
console.log(startMonth);

How to get difference of date in JavaScript Date object? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 3 years ago.
Consider I have an array of dates eg:
abc = [new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")]
output:
[Sun Mar 01 2015 05:30:00 GMT+0530 (India Standard Time), Mon Mar 02 2015 05:30:00 GMT+0530 (India Standard Time), Tue Mar 03 2015 05:30:00 GMT+0530 (India Standard Time), Wed Mar 04 2015 05:30:00 GMT+0530 (India Standard Time)]
I'm trying to push the difference between two dates and trying to store the data in a new array.
Here is what I have tried,
var arr = [];
abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];
for (let i = 0; i < abc.length-1; i++){
arr.push((abc[i+1].getDate() - abc[i].getDate())+1)
}
And the output I'm getting is:
[1,2, 2, 2]
But I needed the output something like
[1,2,3,4]
I need to append plus one to each date difference. How can I achieve that?
Dates in the format YYYY-MM-DD are parsed as UTC, where every day (in ECMAScript) is exactly 8.64e7 ms long making simple arithmetic, well, simple. :-)
Since the dates are whole days and treated as UTC, you can just subtract the dates from each other and divide by 8.64e7 to get whole days difference.
Also, you seem to want the difference from the first date, so hold that constant, e.g.
let arr = [];
let abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];
for (let i = 0; i < abc.length-1; i++){
arr.push(1 + (abc[i+1] - abc[0])/8.64e7);
}
console.log(arr);
Is this what you want?
abc = [new Date("2015-03-01"),new Date("2015-03-01"),new Date("2015-03-02"),new Date("2015-03-03"),new Date("2015-03-04")];
const result = abc.slice(1).map(date => ~~((date-abc[0]) / (24*60*60*1000)) + 1)
console.log(result)

Categories