I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.
Related
When the date is passed from my c# to JavaScript it returns the date time as {4/3/2020 12:00:00 AM}
but in JavaScript it is shown as 1585852200000.
What is the format that is being used? And how can i convert it back?
You need to convert the Unix timestamp to DateTime format,
var localDate = new Date(1585852200000).toLocaleDateString("en-US")
console.log(localDate); // only local date
var localTime = new Date(1585852200000).toLocaleTimeString("en-US")
console.log(localTime) // only local time
// local datetime
console.log(new Date(1585852200000).toLocaleString());
1585852200000 is epoch date.
you can convert it as
var date = new Date(1585852200000)
console.log(new Date(1585852200000));
As an alternative from Shivaji's answer:
When you are passing the date through to JS you could cast it as a string with DateTime.ToString("dd/MM/yyyy") seen here on MSDN.
This will keep its integrity visually, if it is just for display purposes, otherwise you will need to re-cast appropriately in JS (in which case use Shivaji's answer).
JavaScript Date's object will return the DATE object and it's POSITION that is being assigned in your computer. So, when you are working with a date or datetime types, you can use some of the methods that are provided by the Date object, such as getDate() and getDay(). But, a better solution would be to format the Date object itself. For example: use the toString() or toUTCString() methods.
var d = new Date();
document.getElementById("demo").innerHTML = d.toString();
Reference:
https://www.w3schools.com/js/js_date_formats.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Using this:
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
I get a date and time like this 2018-12-30T14:15:08.226Z, but only i want is this 2018-12-30. How can I retrieve just the date?
**This is Fixed. Thank You everyone who helps!!!
You're experiencing a JS problem, it has nothing to do with Angular.
This will use Date methods to get all the data you want:
const date = new Date ();
let dateString = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
// 2018-12-26
You can take advantage of the fact that the ISO 8601 format (what you are getting by implicitely converting to string) is well-codified with a separator T between the date and time in order to split it.
toISOString() gives you what you're seeing. split("T") splits the string into an array of strings with T as separator. [0] then extracts the first element.
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
console.log(myDate.toISOString().split("T")[0]);
I have some code that tries to parse a date string.
When I do alert(Date("2010-08-17 12:09:36"));
It properly parses the date and everything works fine but I can't call the methods associated with Date, like getMonth().
When I try:
var temp = new Date("2010-08-17 12:09:36");
alert(temp);
I get an "invalid date" error.
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Date()
With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString) uses one of these formats:
"October 13, 1975 11:13:00"
"October 13, 1975 11:13"
"October 13, 1975"
The following format works in all browsers:
new Date("2010/08/17 12:09:36");
So, to make a yyyy-mm-dd hh:mm:ss formatted date string fully browser compatible you would have to replace dashes with slashes:
var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));
The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.
For More Information:
Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
I know this is old but by far the easier solution is to just use
var temp = new Date("2010-08-17T12:09:36");
Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function
function Animal(){
this.abc = 1;
return 1234;
}
var x = new Animal();
var y = Animal();
console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Until ES5, there was no string format that browsers were required to support, though there are a number that are widely supported. However browser support is unreliable an inconsistent, e.g. some will allow out of bounds values and others wont, some support certain formats and others don't, etc.
ES5 introduced support for some ISO 8601 formats, however the OP is not compliant with ISO 8601 and not all browsers in use support it anyway.
The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.
/* Parse date string in format yyyy-mm-dd hh:mm:ss
** If string contains out of bounds values, an invalid date is returned
**
** #param {string} s - string to parse, e.g. "2010-08-17 12:09:36"
** treated as "local" date and time
** #returns {Date} - Date instance created from parsed string
*/
function parseDateString(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);
return d && d.getMonth() == b[1] && d.getHours() == b[3] &&
d.getMinutes() == b[4]? d : new Date(NaN);
}
document.write(
parseDateString('2010-08-17 12:09:36') + '<br>' + // Valid values
parseDateString('2010-08-45 12:09:36') // Out of bounds date
);
I was having the same issue using an API call which responded in ISO 8601 format.
Working in Chrome this worked:
`
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date();
var outputDate = eventDate.toDateString();
`
but this didn't work with firefox.
Above answer helped me format it correctly for firefox:
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date(date.replace(/-/g,"/");
var outputDate = eventDate.toDateString();
You can also create single Date object and update it using the static function Date.now() :
<!doctype html>
<html> <head></head>
<body>
<h1 id="datetime"></h1>
<script>
elem_datetime = document.getElementById('datetime');
var date = new Date();
function sometimer()
{
setTimeout(sometimer, 1*1000); // wait 1 second and call again
date.setTime(Date.now());
elem_datetime.innerHTML = date.toDateString() + ' ' + date.toLocaleTimeString();
}
sometimer();
</script>
</body>
</html>
You're not getting an "invalid date" error.
Rather, the value of temp is "Invalid Date".
Is your date string in a valid format?
If you're using Firefox, check Date.parse
In Firefox javascript console:
>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000
I would try a different date string format.
Zebi, are you using Internet Explorer?
I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:
var temp = new Date( Date("2010-08-17 12:09:36") );
alert(temp);
the internal call to Date() returns a string that new Date() can parse.
I need to understand how to do date formattting in javascript.
i have date as,
var date="12/02/1994";// dd/mm/yyy
var date1=new Date(date);
date1.getDate();// this gives me Month which is 02
date1.getMonth();// this gives me date which is 12.
How do i get the exact date i have in var date in get date and getmonth function? Please help
The answer is pretty simple: JavaScript uses mm/dd/yyyy data format.
It doesn't support dd/mm/yyyy format, so, if you need to parse this format, then you will have to do this manually like this:
function parseDdmmyyyy(str)
{
var spl = str.split('/');
return new Date(spl[2], spl[1] - 1, spl[0]);
}
or you will have to use external libraries like Moment.js.
Javascript date() expects date in mm/dd/yy and not in dd/mm/yy. And months start from 0 and not 1.
var from = "12/02/1994".split("/");
var date1 = new Date(from[2], from[1] - 1, from[0]);
date1.getDate();
date1.getMonth();
Use new Date('02/12/1994'), new Date('1994-02-12') or new Date(1994, 02-1, 12), because in js months start from 0 and american date format is used where month goes first
you can use the simple JS file DateFormat.js which has some very good example through the URL mattkruse (Date Funtion)
from this JS file you can validate the incoming date is a true format even you can add format date within a several ways.
Presumably you want to know how to format strings so they are consistently parsed by browsers. The short answer, is there is no guarantee that any particular string will be correctly parsed by all browsers in use (or perhaps even most).
So the bottom line is: don't parse strings with the Date constructor, ever. It's largely implementation dependent and even the one format specified in ES5 and ECMAScript 2015 is poorly and inconsistently supported.
How browsers treat a string like "12/02/1994" is entirely implementation dependent, however most will treat it as the peculiar US month/day/year format, i.e. 2 December and getMonth will return 11, since months are zero indexed.
So you should always manually parse strings (a library can help, but a simple parsing function is only 2 lines, 3 if validation is required), e.g.
// Parse a date string as d/m/y
// If s is not a valid date, return a Date object with its
// time value set to NaN.
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && b[1] == d.getMonth()? d : new Date(NaN);
}
document.write(parseDMY('12/02/1994'));
In javascript you can create a Date object from a string, like
var mydate = new Date('2008/05/10 12:08:20');
console.log(mydate); //=> Sat May 10 2008 12:08:20 GMT+0200
Now try this using milliseconds in the string
var mydate = new Date('2008/05/10 12:08:20:551'); // or '2008/05/10 12:08:20.551'
console.log(mydate); //=> NaN
Just out of curiosity: why is this?
EDIT: thanks for your answers, which all offer sufficient explanation. Maybe in some future there will be support for use of milliseconds in date strings. Untill then I cooked up this, which may be of use to somebody:
function dateFromStringWithMilliSeconds(datestr){
var dat = datestr.split(' ')
,timepart = dat[1].split(/:|\./)
,datestr = dat[0]+' '+timepart.slice(0,3).join(':')
,ms = timepart[timepart.length-1] || 0
,date;
date = new Date(datestr);
date.setMilliseconds(ms);
return date;
}
If you know the different components you can use this overload to the Date constructor:
var mydate = new Date(2008,6,10,12,8,20,551);
Note 6 for the month, as the months go from 0-11.
If needed you can take the string representation and split it to its component parts and pass those through to this constructor:
var datestring = '2008/05/10 12:08:20:551';
var datearray = datestring.split(/\s|:|\//g)
var mydate = new Date(datearray[0], parseInt(datearray[1]) + 1 , datearray[2], datearray[3],datearray[4],datearray[5],datearray[6]);
As described in this document, the string overload should conform to RFC-1123 (which in turn conforms to RFC-822) which does not support milliseconds.
dateString
String value representing a date. The string should be in a format recognized by the parse method (IETF-compliant RFC 1123 timestamps).
This format doesn't seem to accommodate milliseconds in the date... It may be best to just define the date without ms and then call setMilliseconds() afterwards.
The ECMA-262 standard, section 15.9.1.15, does indeed specify milliseconds in the date string format. I'm guessing the browser developers just couldn't be bothered to implement it.