How to parse the year from this date string in JavaScript? - javascript

Given a date in the following string format:
2010-02-02T08:00:00Z
How to get the year with JavaScript?

It's a date, use Javascript's built in Date functions...
var d = new Date('2011-02-02T08:00:00Z');
alert(d.getFullYear());

You can simply parse the string:
var year = parseInt(dateString);
The parsing will end at the dash, as that can't be a part of an integer (except as the first character).

I would argue the proper way is
var year = (new Date('2010-02-02T08:00:00Z')).getFullYear();
or
var date = new Date('2010-02-02T08:00:00Z');
var year = date.getFullYear();
since it allows you to do other date manipulation later if you need to and will also continue to work if the date format ever changes.
UPDATED: Jason Benson pointed out that Date will parse it for you. So I removed the extraneous Date.parse calls.

var year = '2010-02-02T08:00:00Z'.substr(0,4)
...
var year = new Date('2010-02-02T08:00:00Z').getFullYear()

You can simply use -
var dateString = "2010-02-02T08:00:00Z";
var year = dateString.substr(0,4);
if the year always remain at the front positions of the year string.

Related

How to parse the date string in YYYY-MM-DD format [duplicate]

This question already has answers here:
Format JavaScript date as yyyy-mm-dd
(50 answers)
Closed 2 years ago.
I have date string in the format '2020/02/25 23:58:08' . I want to parse it to '2020-02-25".
Note : Initially date is in string format, after conversion whether it is in date or string format it doesn't matter.
file.js
function test (filepath) {
let date = "2020/02/25 23:58:08";
date = date.replace("//"/gi,"-");
// I am not familiar with regular expressions, I want to omit the data related to hours, seconds extra
}
When I ran the program, I gotUncaught ReferenceError: gi is not defined, gi is to globally replace
Try this
let date = "2020/02/25 23:58:08";
var date2 = new Date(date)
console.log(date2.toISOString().slice(0,10))
let date = `2020/02/25 23:58:08`;
let parsedDate = date.split(" ")[0].replace(/\//gi,'-');
console.log(parsedDate);
There is an error in the line using regex, should be:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
Then to get only the date, you can get the first 10 characters:
date.slice(0,10)
Final code:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
date.slice(0,10)
Although there are other ways to do it, you can use a library like momentJs which includes methods for this, like moment.format, it gives so many possibilities. But if you have a small case this is fine.

Get "Day" From This Formatted Timestamp In Javascript

I'm working with Javascript within Google Sheets, and I'm having trouble converting or parsing a formatted timestamp, to ultimately extract the day as a numerical value.
My code:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
Logger.log(date.getDay());
The output:
[19-06-10 17:40:56:107 BST] NaN
My goal is to extract the day number, for example, "18" from that timestamp.
However, it doesn't seem to convert it. I suspect my timestamp isn't in the correct format for the date() function, so it's about creating a function to parse it.
Hopefully, you can help me with that! :) Thank you so much.
The date object has a method like this for getting the day of the month as a number (1-31).
date.getDate();
18 is date.
var shopifyTimestamp ="2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
console.log(date.getDate());
JavaScript's Date constructor supports ISO 8601 date strings. Without using any libraries, you can do something like this:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
// will produce `2019-05-18T13:21:17+0100`
var isoDate = shopifyTimestamp.slice(0, 10)
+ 'T' + shopifyTimestamp.slice(11, 19)
+ shopifyTimestamp.slice(20);
var date = new Date(isoDate);
console.log(date.getDate()); // 18
Also note that you're looking for date.getDate(), rather than date.getDay(). The latter returns the numerical date of the week.

How to remove the letter "Z" from the end of a dateTime

I am trying to remove the Z from the end of a dateTime entity. The timezone of the API gets confused from the site I'm pushing the date from. Does anyone know a script that can remove the Z when a user types in a dateTime?
You're using UTC Date i'm guessing. You can try to use .toLocaleString() on your date time object.
Example
var datetime = new Date();
var now = datetime.toLocaleString();
This should get you something like this: 6/30/2017, 8:47:15 AM
Another option if you want to maintain the format and just remove the T and Z characters is to replace the strings. Example:
var datetime = new Date();
var now = datetime.toISOString().replace('Z', '').replace('T', '');

Javascript: How to convert exif date time data to timestamp? [duplicate]

This question already has answers here:
javascript: how to parse a date string
(4 answers)
Closed 5 years ago.
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.
The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.
How to solve this problem?
Thanks in advance.
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:
/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}
console.log(parseDate('2017:03:09 14:49:21').toString());
It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:
var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
You can do simple string manipulation and create date if the format is always the same, as:
var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);

How to get the date object

My value contains "08.07.1987", how to retrieve the date object for this string. new Date(val) gives correct date object values only for the string value that contains "/" format. can any one let me know hot to create date object for the values which contains "." or "-". in its format.
How about just adjusting the string to suit your needs?
var date1 = new Date("08.07.1987".replace('.','/'));
var date2 = new Date("08-07-1987".replace('-','/'));
You will need to be careful when asking Javascript to interpret a date in this format. As you can probably imagine, a date listed as "08.07.1987" doesn't really specify whether it's August 7th or July 8th.
In general, your best bet will be to specify a date format and parse accordingly.
you have to split the string into tokens for month date and year and then create it using JS Date API.
var date="08.07.1987";
var newDate = date.replace(/(\.|-)/g,"/"));
var dateObject = new Date(newDate);
Replace the delimiters?
var dateStr = "08.07.1987",
dateObj = new Date(dateStr.replace(/[-.]/g,"/"));
Of course you can encapsulate that in a function if need be...
try this new Date("08.07.1987".replace('.','/','g')); tested on firefox only

Categories

Resources