i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:
var from = $("#datepicker").val();
var to = $("#datepickertwo").val();
var f = new Date(from);
var t = new Date(to);
("#datepicker").val() contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":
alert(f);
Is this because of the '-' symbol? How can I overcome this?
Split on "-"
Parse the string into the parts you need:
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Use regex
var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
Why not use regex?
Because you know you'll be working on a string made up of three parts, separated by hyphens.
However, if you were looking for that same string within another string, regex would be the way to go.
Reuse
Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:
function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
Using as:
var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
Or if you don't mind jQuery in your function:
function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
Using as:
var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
Modern JavaScript
If you're able to use more modern JS, array destructuring is a nice touch also:
const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
regular expression example:
new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );
Another possibility:
var from = "10-11-2011";
var numbers = from.match(/\d+/g);
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);
Match the digits and reorder them
Using moment.js example:
var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)
Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00
var from = $("#datepicker").val();
var f = $.datepicker.parseDate("d-m-Y", from);
You can also write a date inside the parentheses of the Date() object, like these:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)
In my case
new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))
Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET)
then I use .getTime() to work with milliseconds
The accepted answer kinda has a bug
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:
var f = new Date(7980, 77, 77);
=> Date 7986-08-15T22:00:00.000Z
Which is probably not the desired result.
The reason for this is explained on the MDN site:
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).
A better way to solve the problem is:
const stringToDate = function(dateString) {
const [dd, mm, yyyy] = dateString.split("-");
return new Date(`${yyyy}-${mm}-${dd}`);
};
console.log(stringToDate('04-04-2019'));
// Date 2019-04-04T00:00:00.000Z
console.log(stringToDate('77-78-7980'));
// Invalid Date
This gives you the possibility to handle invalid input.
For example:
const date = stringToDate("77-78-7980");
if (date === "Invalid Date" || isNaN(date)) {
console.log("It's all gone bad");
} else {
// Do something with your valid date here
}
You can use an external library to help you out.
http://www.mattkruse.com/javascript/date/source.html
getDateFromFormat(val,format);
Also see this: Parse DateTime string in JavaScript
You can just:
var f = new Date(from.split('-').reverse().join('/'));
let dateString = '13-02-2021' //date string in dd-mm-yyyy format
let dateArray = dateString.split("-");
//dateArray[2] equals to 2021
//dateArray[1] equals to 02
//dateArray[0] equals to 13
// using template literals below
let dateObj = new Date(`${dateArray[2]}-${dateArray[1]}-${dateArray[0]}`);
// dateObj equals to Sat Feb 13 2021 05:30:00 GMT+0530 (India Standard Time)
//I'm from India so its showing GMT+0530
P.S : Always refer docs for basics, MDN or DevDocs
Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too
You could use a Regexp.
var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
from = new Date(
parseInt(result[3], 10),
parseInt(result[2], 10) - 1,
parseInt(result[1], 10)
);
}
new Date().toLocaleDateString();
simple as that, just pass your date to js Date Object
Related
I have a form set-up in such a way that I collect the dates from a different input box and time from a dif
var appointment_date = new Date();
var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)");
var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT-0400 (EDT)");
console.log(appointment_date);
console.log(appointment_start);
console.log(appointment_end);
let selected_day = appointment_date.toString().split(' ').slice(0, 1).join(' '),
selected_date = appointment_date.toString().split(' ').slice(1, 2).join(' '),
selected_month = appointment_date.toString().split(' ').slice(2, 3).join(' '),
selected_year = appointment_date.toString().split(' ').slice(3, 4).join(' ');
console.log(selected_day);
console.log(selected_date);
console.log(selected_month);
console.log(selected_year);
console.log(appointment_start.toString().split(' ').slice(4, appointment_start.toString().length).join(' '));
console.log(new Date(selected_year, selected_month, selected_date, appointment_start.toString().split(' ').slice(4, appointment_start.toString().length).join(' ')));
ferent input field.
I tried converting my Date and Time to string; splitting them and then joining it with the other time but it's not giving me the proper time. Is there a better way to do this?
where this.state.appointment_date = new Date();
this.state.appointment_start = new Date();
this.state.appointment_end = new Date();
let selected_day = this.state.appointment_date.toString().split(' ').slice(0, 1).join(' '), // Day
selected_date = this.state.appointment_date.toString().split(' ').slice(1, 2).join(' '), // Date
selected_month = this.state.appointment_date.toString().split(' ').slice(2, 3).join(' '), // Month
selected_year = this.state.appointment_date.toString().split(' ').slice(3, 4).join(' '); // Year
console.log(this.state.appointment_start.setDate(selected_day)); //NaN (output)
console.log(this.state.appointment_start.toString().split(' ').slice(4, this.state.appointment_start.toString().length).join(' ')); // no output
console.log(this.state.appointment_end.toString().split(' ').slice(4, this.state.appointment_end.toString().length).join(' ')); //time
// I tried to create a new date using the above date:
console.log(new Date(selected_day, selected_month, selected_date, selected_year, this.state.appointment_start.toString().split(' ').slice(4, this.state.appointment_start.toString().length).join(' ')));
But I get invalid date for it. Not sure how to do it :/
This way I was trying to break it up and then combine it again to create the final date. But this seems like a really long approach for something which should be simpler
Expected Input/Output:
Input: dates in the same format as new Date()
Output: Take day, month and year from appointment_date and time from appointment_start and create a new date object
The correct syntax of Date is
new Date(year, month, day, hours, minutes, seconds, milliseconds);
so you mess the supplied params.
The selected_day in your case will produce the name of the day.
In your code:
var appointment_date = new Date();
var appointment_start = new Date("Mon Apr 24 2017 20:00:00 GMT-0400 (EDT)");
var appointment_end = new Date("Mon Apr 24 2017 21:30:00 GMT-0400 (EDT)");
You should not parse strings with the Date constructor (or Date.parse) as it's largely implementation dependent. The standard does not require a string in this format to be parsed correctly. If you want to create some test dates, use:
var appointment_start = new Date(2017, 3, 24, 20);
assuming that your time zone is -0400. The first part of your code can be rewritten as:
var appointment_date = new Date();
var appointment_start = new Date(2017, 3, 24, 20);
var appointment_end = new Date(2017, 3, 24, 21, 30);
console.log(appointment_date.toString());
console.log(appointment_start.toString());
console.log(appointment_end.toString());
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var selected_day = days[appointment_date.getDay()],
selected_date = appointment_date.getDate(),
selected_month = appointment_date.getMonth() + 1,
selected_year = appointment_date.getFullYear();
console.log(selected_day);
console.log(selected_date);
console.log(selected_month);
console.log(selected_year);
let selected_day = appointment_date.toString().split(' ').slice(0, 1).join(' '),
This depends on the output of Date.prototype.toString having a particular format, however ECMA-262 allows the format to be implementation dependent, so it may have a different format in different hosts. See Where can I find documentation on formatting a date in JavaScript?
Consider using a library, or write your own small formatter if you only have one format to support.
Where you have:
console.log(this.state.appointment_start.setDate(selected_day)); //NaN (output)
You are passing a value like "Tue" (or maybe something completely different) instead of a date, so the result is NaN.
In the last line you have:
console.log(new Date(selected_year, selected_month, selected_date,
appointment_start.toString().split(' ').slice(4,
appointment_start.toString().length).join(' ')));
Which attempts to build a Date by passing values for the first three parameters, but then tries to pass all the parts for the time as a single string. You need to pass all the parts as individual values. Also, months are zero indexed so you need to subtract 1.
But there is no need for such convoluted code, all the parts of the date are available using Date methods, see Where can I find documentation on formatting a date in JavaScript? as noted above.
I have the upload date for a course saved in a ViewModel variable #Model.Course.UploadDate when calling the following code:
alert('#Model.Course.UploadDate');
I get an output as expected of:
21/01/2014 16:16:13
I know want to check that the uploadDate is within the last 10 seconds before sending a statement to the database but trying to use the following code:
var uploadDate = new Date('#Model.Course.UploadDate.ToLongDateString()');
alert("UPLOAD DATE " + uploadDate);
I get an unexpected output of:
Tue Jan 21 2013 00:00:00 GMT+0000
This is the format that I need the date in only with the saved time data shown. I am then looking to perform a calculation as follows:
var TENSECONDS = 10 * 1000;
var uploadDate = new Date('#Model.Course.UploadDate.ToLongDateString()');
var today = new Date();
var check = today - uploadDate;
if (parseInt(check) > parseInt(TENSECONDS))
alert("ROUTE1");
else
alert("ROUTE2");
Quote from the documentation of the Date object constructor:
value: Integer value representing the number of milliseconds since 1
January 1970 00:00:00 UTC (Unix Epoch).
So actually that's the safest thing to pass to the constructor of a Date object instead of some strings which might be incorrectly interpreted and are completely culture dependent.
So just convert your DateTime instance to the number of milliseconds that elapsed since 1 January 1970 and feed this timestamp to the constructor:
var timestamp = #(Model.Course.UploadDate - new DateTime(1970, 1, 1)).TotalSeconds;
var uploadDate = new Date(timestamp);
As an alternative you could use the ISO8601 format if you intend to be passing a string:
dateString: String value representing a date. The string should be in
a format recognized by the Date.parse() method (IETF-compliant RFC
2822 timestamps and also a version of ISO8601).
So:
var uploadDate = new Date('#Model.Course.UploadDate.ToString("o")');
I solved this using the following code:
var dateArray = new Array();
dateArray = '#Model.Course.UploadDate'.split("/");
var dateD = dateArray[0];
var dateM = dateArray[1];
var dateY = dateArray[2];
var dateT = dateArray[3];
timeArray = dateT.split(":");
var timeH = timeArray[0];
var timeM = timeArray[1];
var timeS = timeArray[2];
var dateUS = dateM + "/" + dateD + "/" + dateY + dateT;
var uploadDate = new Date(dateD,dateM,dateY,timeH,timeM,timeS);
I'm trying to display a date with format "MMM. dd HH:mm:ss.nnn". It is rendering it incorrectly in IE and I have spent quite some time and I can't figure out why I can't get this to work.
I know that Date.UTC returns the number of miliseconds in a Date object since Jan 1, 1970. So,
var newDate = new Date(Date.UTC(year, month[, date[, hrs[, min[, sec[, ms]]]]])
newDate.toString("MMM. dd HH:mm:ss.")+row.timestamp.getMilliseconds();
will work.
Example:
var newDate = new Date(Date.UTC(1950, 10, 10, 10, 09, 09, 100));
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Nov. 10 05:09:09.
But, I am interating this from a jquey.each function so the date string that I am working with is an ISO 8601: "2013-03-12T15:14:10.483". So, this is what I have in mind.
var numMilisecond = Date.parse(row.timestamp);
var newDate = new Date(numMilisecond);
row.timestamp_f = newDate.toString("MMM. dd HH:mm:ss."); // Output => Dec. 31 19:00:00.
row.timestamp is from a JSON response
{"timestamp":"2013-03-12T15:14:10.483" ...}
Why doesn't the code work? Date.parse should return the number of miliseconds since Jan 1, 1970 and then I create a new Date obj and then convert it to string just like the code in the first snipet. What am I doing wrong?
Thanks.
Date.toString shouldn't accept any arguments. If you want a true date-formatting solution, you'll need to use a plugin or roll your own.
var shortmonths = ['Jan','Feb','Mar','Apr',]; // remaining months are left as an exercise for the reader
row.timestamp_f = shortmonths[newDate.getMonth()]
+ ". "+newDate.getDate() + " "
+ newDate.toLocaleTimeString() + ".";
How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);
I want to parse date in the format ddMMyyhhmm (eg 2804121530 representing 28th April 2012, 3:30 PM) to javascript Date() object.
Is there any oneliner solution to it? I'm looking for something of the kind:
var date = Date.parse('2804121530', 'ddMMyyhhmm');
or
var date = new Date('2804121530', 'ddMMyyhhmm');
Thanks for help!
A useful library here is DateJs. Just add a reference:
<script src="http://datejs.googlecode.com/files/date.js"
type="text/javascript"></script>
and use Date.parseExact:
var dateStr = '2804121530';
var date = Date.parseExact(dateStr, 'ddMMyyHHmm');
For a fast solution you can brake that string into pieces and create date from those pieces
function myDateFormat(myDate){
var day = myDate[0]+''+myDate[1];
var month = parseInt(myDate[2]+''+myDate[3], 10) - 1;
var year = '20'+myDate[4]+''+myDate[5];
var hour = myDate[6]+''+myDate[7];
var minute = myDate[8]+''+myDate[9];
return new Date(year,month,day,hour,minute,0,0);
}
var myDate = myDateFormat('2804121530');
or a simper solution:
function myDateFormat(myDate){
return new Date(('20'+myDate.slice(4,6)),(parseInt(myDate.slice(2,4), 10)-1),myDate.slice(0,2),myDate.slice(6,8),myDate.slice(8,10),0,0);
}
var myDate = myDateFormat('2804121530');
(new Date(1381344723000)).toUTCString()
Correct me if 'm worng...