How to extract only the year from a date string? [duplicate] - javascript

This question already has answers here:
Keep only first n characters in a string?
(7 answers)
Closed 3 years ago.
Is there a way to grab only the first four characters of a date string from an API in JavaScript?
Back story
I am using The Movie Database, which allows me to get the exact release dates of movies. For instances, I get the following object of data for "Finding Nemo":
I've added the following code in my Movies.js component, <p>({movie.release_date})</p>
and it returns 2003-05-30 as expected.
But is there a way to extract only the first four characters (2003) and return only that? Or better yet, is there a way to extract only the release year?

There are a few ways you can do this, each method is fairly similar. The below are fairly simple and straight forward to use.
Split at '-'
const date = "2020-01-01";
const year = date.split("-")[0];
alert(year);
This method separates the string where ever there is a '-' and stores each section in an array. You want the first section, the one located in the first spot or with an index of 0. This is probably the easiest and most straight forward method, you can learn more about it here
Slice method
const date = "2020-01-01";
const year = date.slice(0, 4);
alert(year);
This method works by slicing the characters from an index of 0 to an index of 4 off of the string returning them in the constant year.
Substr method
This method was already referenced in this thread by #larz so I won't bother adding an example or explaining it as they can be found in their answer.
I hope this helps, for more information or you want to explore more methods take a look at this link

You can use the substring function on a string, providing the character to start with (0 is the first, like an array) and how many characters to grab.
const date = "2020-01-01";
const year = date.substring(0, 4);
alert(year);

You can achieve extracting only the release year in the following way
const d = new Date( movie.release_date );
d.getFullYear();

Related

How do you exclude only some numbers from string input on Javascript? [duplicate]

This question already has answers here:
How can I delete a query string parameter in JavaScript?
(27 answers)
Closed last month.
So I'm wanting to figure out how do you exclude on some numbers from a string input. For example, If I were to input this "https://www.shoepalace.com/products/jordan-dr6287-486-air-jordan-5-low-doernbecher-mens-lifestyle-shoes-blue-multi?variant=41679925772494", I'd want "?variant=41679925772494" remove and keep the rest the same. I can't use a constant of "?variant=41679925772494" because I'm wanting it work across all string inputs, not the same one. what I have is below, but it removes all numbers within the link, rather than whats after "?variant=". Does anyone have any ideas on how I can go about this?
let updatedLink = link.replace("?variant=", "")
let variantLink = updatedLink.replace(/[0-9]/g, "")```
If you want to parse URL's, using regex is not really the best option.
Browsers have the URL class that does exactly what your after.
eg.
var n = new URL('https://www.shoepalace.com/products/jordan-dr6287-486-air-jordan-5-low-doernbecher-mens-lifestyle-shoes-blue-multi?variant=41679925772494');
n.searchParams.delete('variant');
console.log(n.toString());

Regex to grab all text before a formatted time (HH:MM) [duplicate]

This question already has answers here:
How can I match "anything up until this sequence of characters" in a regular expression?
(15 answers)
Closed 5 months ago.
I am trying to parse time bookings looking like this:
14687 - Project foobar, homeOffice 7:40 - 13:59
436 - Project barfoo, office 12:49 - 22:00
I want to grab all the text before the first occurrence of a time. The time has the 24 hour format HH:MM without leading zero. There can be one or two occurrences of such a timestamp.
I figured this is the RegEx to match the time in this format:
(\d?\d:\d\d)
But how would I get the text before it?
I am using javascript.
I actually prefer a regex replacement approach here:
var input = "14687 - Project foobar, homeOffice 7:40 - 13:59";
var text = input.replace(/\s*\d{1,2}:\d{2} - \d{1,2}:\d{2}$/, "");
console.log(text);
This approach has an advantage over using match() with a capture group. With the above approach, we just return the entire input if it does not end in an hour range.

How to combine Date and Time from 2 different var's in NodeJS

I have a User Input which consists of a Date and a Time Input. Both of those values are send as a full date like
reminder_date: '2021-02-15T08:00:00.000Z',
reminder_time: '2021-02-09T17:00:00.000Z'
But i want to store it in my db as one single value like
'2021-02-15T17:00:00.000Z'
what is the best approach to achieve that ? split the strings on T and then combine or is there a simple way i can take the date part and the time part and create a new dateTime to save
If the two items are strings, you could simply use the JavaScript substr function to get the first 11 characters from reminder_date and the second part of reminder_time (starting from 11), then concatenate them, e.g.
let reminder_date = '2021-02-15T08:00:00.000Z';
let reminder_time = '2021-02-09T17:00:00.000Z';
let reminder_date_time = reminder_date.substr(0, 11) + reminder_time.substr(11);
console.log(reminder_date_time);

How to convert a non-delimited strings like MMDDYYYY to MM-DD-YYYY [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need to create a generic function to convert user input in well formated date string like DD-MM-YYYY.
For example -
I have a string 27031990 I want to convert this into 27-03-1990. Similarly, if user has put in 2731990 it should get converted into 27-03-1990
You could try using a regular expression to split the date into it's components.
/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4}|\d{2})$/gm
Example usage:
const datePattern = /^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4}|\d{2})$/gm;
const date = '2-12-18';
let [, day, month, year] = datePattern.exec(date);
Here's a function you can use for padding the a string with an arbitrary number of zeroes:
function zeroPad(string, digits) {
const zeros = Array(digits).fill('0');
return (zeros + string).slice(-digits);
}
So you'd use this as
date = zeroPad(day);
month = zeroPad(month);
And then you could use a conditional for converting years in YY format to YYYY perhaps using the 19 prefix if the year is greater 18 or 20 otherwise. Just an example, but hopefully you get what I mean.
Edit 1: As #Daniel suggested, you could use ES2017's String.prototype.padStart rather than using the ad-hoc zeroPad function.
Edit 2: If you want it to work with non-delimited strings, the date will have to be either in DDMMYY format or in DDMMYYYY to avoid ambiguity as #Teemu pointed out in the comments to your question. You could implement this is in regex as /^(\d{2})[\/\-]?(\d{2})[\/\-]?(\d{4}|\d{2})$/gm
Edit 3: #CertainPerformance suggested destructuring the matches immediately. I've incorporated this.
Take the input and split it by either / delimiter or - delimiter by using a regex seperator:
.split(/[\/-]/);
Then map the result using the ES2017 function padStart() so that 0's are prepended if neccesary
.padStart(2, "0")
Finally, join the array with the dash symbol (-) and you should have your result.
Example
let input = "27/03/1990";
let result = input.split(/[\/-]/).map(i => i.padStart(2, "0")).join('-');
console.log(result);
May be you can extract the in index of non numeric charachter and call subString() function till that for initial array index. Then use the same for month and year till you reach the end of the string.

parseInt not working with data from an Array created from a spitted Date inside Angularjs controller [duplicate]

This question already has answers here:
ToLocaleDateString() changes in IE11
(5 answers)
Closed 7 years ago.
I have a date that I am converting to LocaleDateString and then splitting it into an array inside an angulrajs controller. When I try to convert to int the elements in the array I get NaN. The characters in the array are numbers but the parse is not working.
How can I parse that data properly?
Code:
var dateLocal = $scope.startDate.toLocaleDateString(); //Has this ‎6‎/‎5‎/‎2015
var dateSplitted = dateLocal.split("/"); //Has [6,5,2015]
var month = parseInt(dateSplitted[0]); //HERE If I use parseIntI get NaN originally it has 6
var day = dateSplitted[1];//Has 5
var year = dateSplitted[2]; Has 2015
I want to be aple to convert to string month day and year.
You rely on toLocaleDateString, which is implementation dependent:
This function returns a String value. The contents of the String are
implementation-dependent
The problem is that your browser returns a string with some left-to-right marks (U+200E).
See the difference:
var str1 = "6", // "\u0036" <-- OK
str2 = "‎6‎"; // "\u200e\u0036\u200e" <-- Your "corrupted" string
parseInt(str1); // 6
parseInt(str2); // NaN
So you shouldn't trust the value returned by that method. Instead, use date methods to get the day, month and year.
This doesn't answer why you are getting NaN in your code, but instead of converting the date object to a string and parsing the parts, you can get the parts of the date directly using Date.prototype.getMonth(), Date.prototype.getDate() (day-of-month), and Date.prototype.getFullYear().
I tried out your code, and it seemed to work fine for me. For your dateLocal, I just replaced your value with var dateLocal = new Date().toLocaleDateString(); because I didn't know what value was loaded from your scope. When I did this, the code loaded fine, so you may want to double check the nature of the variable you are loading from the scope.

Categories

Resources