Given string format to date - javascript

I have given a very unusual date format in string. I need to convert it to a JS date object and add up a few days. The last step is clear, but I don't know how to convert the string into the JS date object. Take a look at the string date: October 02, 2016

You should use moment.js
Syntax:
moment(dateString, format, locale)
var dateStr = "Oktober 02, 2016"
var d = moment(dateStr, "MMM DD, YYYY", 'de');
console.log(d.format("DD-MM-YYYY"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment-with-locales.min.js"></script>

Use Date.parse() to parse the date and get the Date object.
var dateObj = new Date('October 02, 2016')
Now, you can perform all the Date operations on dateObj

Given that everything is static here, I thing the best case for you might be to keep a map of your month's name against there number i.e say Oktober : 8. This way you will easily get around of any locale issue in any library.
Once above map is done, you can use .substring to separate your string for blank space and commas to get date and year easily.
Once you have all this you can use new Date constructor with months date and year field.
Hope this all is easily understood, so I am skipping any code here.

Using new Date() can be converted from string to date.
And using setDate() you can add days in the date and can convert the date back to string,
Please check below snippet for more understanding.
var someDate = new Date('October 02, 2016');
console.log(someDate);
console.log(new Date(someDate.setDate(someDate.getDate() + 5)).toString());

Related

JavaScript input date convertion

Is there any way to convert any date string (not necessarily current date) (could be any format) to specific date format in Javascript. Like converting "MM-DD-YYYY" or "ddMMYYYY" to "DD-MMM-YYYY"?
I know that from current date as var date = new Date(), we can get time and hours but what to do in case of existing date string like "31/01/1999" to "31-JAN-1999".
Given the input date string can be of any format.
This is a common problem.
You should be able to do it with moment.js.
Ex.
moment("31/01/1999").formatWithJDF("dd - MM - yyyy");
Have a look here, https://momentjs.com/docs/ for more details.
Using DateFormatter.js
var date = new Date('2020-03-25 10:30:25');
var formatter = new DateFormatter();
displayFormat = 'D M d Y h:i:s';
var dateString = formatter.formatDate(date, displayFormat); // Wed Mar 25 2020 10:30:25
This can be done by first checking the input date format with the arrays or Map of regex provided, then need to convert that format to JS accepted format ISO format.
Once converted to ISO format this date now can be converted to any form with logic written for it in separate functions.

I get a different date

I need date format like : 2018-10-04T20:35:28. in javascript.
I don't know what format is this, but I already try follow
Now I have this:
var now = new Date();
var isoDate = new Date(now).toISOString();
My output is:
2018-10-05T04:55:58.896Z
But I have a wrong day because actual date is:
Thu 4 Oct 2018 22:56:53 CST
Why i have +1 day in all dates.
like #Nisarg Shah said "The ISO string is in UTC, the one in console is in your local time zone" . You can change it using this
new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
Check this out for more information.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
var isoDate = new Date(now).toISOString();
// Output
2018-10-05T04:55:58.896Z
This isoDate is in UTC. You can see that there is a 'Z' in the end of the string. This means that the date is in UTC.
You can use Moment Timezone (moment.js) to convert any given date to another timezone.
moment.tz('2018-10-05T04:55:58.896Z', 'America/Toronto').format();
Just change the timezone name to the one you want to convert.
For Further Details
https://momentjs.com/timezone/docs/#/using-timezones/

Cannot create a new Date() object from a date that contain milisec '2015-05-14 08:08:48.792'

var newDate= new Date('2015-05-14 08:08:48.792');
console.log(newDate);
If I run the code above I get the following: Date {Invalid Date}.
I have this problem in firefox, in chrome it works.
I need to create this object because I need to do difference between two dates that contains milliseconds.
e.g. '2015-05-14 08:08:48.792' - '2015-05-14 08:08:50.792'
You should be using a recognised format when dealing with date strings.
If you look at the Mozilla documentation for the Date constructor, the dateString overload accepts a string representing the date formatted as it would be valid for Date.parse().
Date:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Date.Parse:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I would suggest ISO8601 as it is generally more supported;
'2015-05-14T08:08:48.792Z'. Notice the T indicating the start of the time segment of the pattern, and preferably the ending Z indicating this is in UTC time.
var newDate = new Date('2015-05-14T08:08:48.792Z');
document.write(newDate);
Updated fiddle: https://jsfiddle.net/7tkmjszv/1/
Hope this helps! :)
Not sure you can use that Date String format for a New Date in JS.
Try to parse and
var newDate = new Date('2015', '05', '14', '08', '08', '48', '792');

Easy way to convert a string that is formatted as a date into a Date object in Javascript?

I have a date string that looks like this: 2014-07-21T12:55:31.513Z. Is there some simple way to convert this to a date? I found that there is Date.parse() however that dives me milliseconds since Jan. 1st, 1970 which it doesn't look like that fits my needs.
new Date("2014-07-21T12:55:31.513Z")
You should also have a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
use
new Date('2014-07-21T12:55:31.513Z')
the ISO format:
YYYY-MM-DD
or
YYYY-MM-DDTHH:MM:SS
refer Date
Note: Where Date is called as a constructor with more than one
argument, if values are greater than their logical range (e.g. 13 is
provided as the month value or 70 for the minute value), the adjacent
value will be adjusted. E.g. new Date(2013,13,1) is equivalent to new
Date(2014,1,1), both create a date for 2014-02-01 (note that the month
is 0-based). Similarly for other values: new Date(2013,2,1,0,70) is
equivalent to new Date(2013,2,1,1,10) which both create a date for
2013-03-01T01:10:00.
Not sure if this is the best way but I would just parse the string to isolate the year, month, day, hours, minutes, seconds and milliseconds the use the following function:
var date = new Date(year, month, day, hours, minutes, seconds, milliseconds);

javascript date format using dateFormat String

I am working on Javascript dates, I have one date which is in the form of 20 Jun 13, I
need to convert it into a Date Object, I used Date.parse() which returns 1 June 2013.
var frmDt = '20 Jun 13';
alert(Date.parse(frmDt));
Which is the solution?
I found date handling in javascript made extremely easier by using momentJs, which allows you to construct moment objects that actually wrap native javascript Date objects in a very liberal way, passing in strings of many different formats and actually being able to get a date object, in a way that is way more reliable than Date.parse().
You can also pass in a date format string, so your case would be something like moment('20 Jun 13', 'DD MMM YY').
d3.js has very robust capabilities for parsing and formatting dates. See https://github.com/mbostock/d3/wiki/Time-Formatting.
I have taken the code posted in my comment and turned it into a function, made the jan,feb,mar case insensitie and the seperator character between day month year can be any character (as long is there is one). so any format dd mmm yy or dd/mmm/yy or d mmm yy will work:
function toDate(str){
var months={
"JAN":1,
"FEB":2,
//... other months
"JUN":6,
//... other months
"DEC":12
}
var r=/^(\d{1,2}).(\w{3}).(\d{2}$)/;
if(r.test(str)===false){
throw new Error("Invalid date string:"+str);
}
var replaceFunction=function(){
var years=parseInt(arguments[3],10);
var m=months[arguments[2].toUpperCase()];
if(typeof m==="undefined"){
throw new Error("Invalid month name:"+arguments[2]);
}
var days=arguments[1]
m=(m<9)?"0"+m:m;
days=(days.length===1)?days="0"+days:days;
years=(years>50)?years="19"+years:"20"+years;
return m+"/"+days+"/"+years;
};
return new Date(str.replace(r,replaceFunction));
}
console.log(toDate("20 Jun 13"));

Categories