Convert string date to datetime js [duplicate] - javascript

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 1 year ago.
I'm stucked on javascript.
I get thi example string from JSON :
Saturday 14th August
How can i convert it in
14/08/2021
Thanks.

You can do it with Pure Javascript with much more logic. My suggestion is to use Moment.Js It's a really easy way to handle complex DateTime data.
Check this working code:
const dateString = "Saturday 14th August";
const formattedDate = moment(dateString, "dddd Do MMMM").format("DD/MM/Y");
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
NOTE:
As #svarog mentioned in the comment, It's hard to find the year, If it's not provided. But the common practice is getting the current year. Moment JS handles this very well.

let jsonDateString = "Saturday 14th August"
//this is the string you get
let jsonDateStringArray = jsonDateString.split(" ");
//here we split the words so we can better manipulate them
let month = jsonDateStringArray[2];
//we save the month here
let day = jsonDateStringArray[1].replace(/\D/g, "");
//saving the day and removing everything but numbers
let year = new Date().getFullYear();
//creating a date so we can get the year without having to hardcode it
let completeDate = new Date(Date.parse(month + ' ' + day + ', ' + year));
//create a new date from the string we pass 'August 14, 2021'
console.log(completeDate.toLocaleDateString('en-GB'));
//parameter en-GB for 14/08/21, without parameter we get 08/14/2021

Related

How do I reformat the date from openweather api using javascript? [duplicate]

This question already has answers here:
Format a date string in javascript
(7 answers)
Closed 2 years ago.
How do I format the date I receive from openweather api?
I currently get 2020-10-16 00:00:00 and I want 10-16-2020.
The reason I don't use moment is because I want future dates which come automatically with the 5 day forecast in the api.
You can use JavaScript's Date object.
You might save yourself time by searching a bit more before posting a question, the answer is probably already out there.
Where can I find documentation on formatting a date in JavaScript?
How to format a JavaScript date
Format JavaScript date as yyyy-mm-dd
You could try to:
Make a new date based on the date that comes from OpenWeather api
Convert it to a LocaleDateString using the 'en-US' locale. This will make the month appear before the date.
Then just split the Date String on the '/' and join in on a '-'. This will substitute the '/' with a '-'
const date = new Date("2020-10-16 00:00:00").toLocaleDateString('en-US');
const formatedDate = date.split('/').join('-');
console.log(formatedDate);
You can always use the built in Javascript Date object.
In your case you'd want to. do something like this -
const myDate = new Date('2020-10-16 00:00:00');
const date = myDate.getDate();
const month = myDate.getMonth() + 1;
const year = myDate.getFullYear();
console.log('MM-DD-YYYY', `${month}-${date}-${year}`);
If you want something more convinient and don't want to use moment you can also try some other popular date libraries. You can find some here - https://github.com/you-dont-need/You-Dont-Need-Momentjs

Why is moment converting this date incorrectly? [duplicate]

This question already has answers here:
moment.js - UTC gives wrong date
(3 answers)
Closed 3 years ago.
I have a GMT date and time format coming from my dynamodb which I'm trying to convert to EST format using momentjs.
2019-06-27 20:00:43.156257
As soon as I drop the date into moment, it's converting it to +4 hours (when its supposed to be -4).
2019-06-28T00:00:43.156Z
All I'm doing is this.
const dbdate = [value-from-db]
const momentdate = moment(dbdate);
My output looks like:
dbdate: 2019-06-27 20:00:43.156257
momentdate: 2019-06-28T00:00:43.156Z
There are two issues here:
1) Moment is performing timezone conversion using your local timezone - use moment.utc instead
2) Your date is not in a format that moment "officially" supports - although actually it's relaxed enough to parse your string. Ideally, it should be provided in proper ISO 8601 format to avoid any compatibility issues.
You could try something like:
const dbdate = '2019-06-27 20:00:43.156257'.split(' ');
const momentdate = moment.utc(dbdate[0] + 'T' + dbdate[1] + 'Z');
alert(momentdate);
Here's a fiddle.
Hope this helps!
You must use moment.utc() instead of moment():
const dbdate = '2019-06-27 20:00:43.156257';
const momentdate = moment(dbdate);
const utcmomentdate = moment.utc(dbdate);
console.log('local: \n', momentdate);
console.log('utc: \n', utcmomentdate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

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);

Javascript...add one day to date and change the format [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I have this date here 2013/06/10, which comes from the database and is set in a variable called date.
I added one day to this date by doing this..
var endDate = new Date(date);
endDate.setDate(endDate.getDate() + 1);
and now I am trying to change the format to yyyy/MM/dd
var finalEndDate = endDate.toString('yyyy/MM/dd');
alert(finalEndDate);
but this returns
Tues Jun 11 2013 Eastern Standard Time, etc.
How do I fix this?
As far as I know, toString does not take any arguments. It's easy to construct your format though.
var finalEndDate = endDate.getFullYear() + '/' + (endDate.getMonth() + 1) + '/' + endDate.getDate();
There are several getter methods for each component of the date object to help you construct nearly any format.
I strongly encourage you to take a look at Moment.js
var str = moment(date, 'YYYY/MM/DD').add('days', 1).format('yyyy/MM/dd');
Note: moment doesn't know yyyy, what's that supposed to be? See http://momentjs.com/docs/#/displaying/format/ for supported format strings.

How to parse the year from this date string in 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.

Categories

Resources