Convert UTC date format into javascript format - javascript

How can I convert a date from:
Thu, 1 July 2011 22:30:00 to '2011-07-01T13:51:50.417' using javascript.
I get the UTC format when I do a new date.
IE causes me issues when I first create a date object as it shows: NaN

You could generate a new Date-Object and then get the different parts:
var today = new Date();
var year = today.getFullYear(); // Returns 2012
var month = today.getMonth()+1; // Returns the month (zero-based)
...
Then you can create a new string like you need it.

possible duplicate try search next time
stackoverflow question
Try http://www.datejs.com/. It is a JavaScript Date Library with an extended Date.parse method and a Date.parseExact method, which lets you specify a format string. See DateJS APIDocumentation.
and then you can manipulate it as you want

The d3.js library has some very solid routines for date conversions. See https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-parse.

Related

Problems trying to get the correct date with Date() and moment.js

I need to convert a date initially given as a string in the format "dd/mm/yyyy" to a valid date object but I'm running into problems. I use the moment.js library for this but when I try to convert it to a date object, it treats it internally incorrectly.
Initially I have:
var date_text = '02/01/2020 00:10'; //i.e. January 2, 2020.
var initial_date = new Date(date_text); //here js takes its default format and the problem starts.
var a = moment(initial_date,'DD/MM/YYYY');
console.log(a); //it keeps telling me that the date is February 1, 2020.
I have seen that this is often done "manually", i.e. by changing the order of the month and day. However, I find it hard to believe that a library as comprehensive and powerfull as moment.js has no way of doing this. I guess I haven't figured out how to do it.
Please, can someone help me in this regard?
What I specifically need is to pick up the date correctly (January 2nd and not February 1st) and preferably do it without having to alter the date "manually", that is, doing it only with the Date object of js and moment.js.
Thank you very much.
You don't really need initial_date to format the date_text when you are using moment.js Try the below code to fix the date parse issue
var date_text = '02/01/2020 00:10'; //i.e. January 2, 2020.
var a = moment(date_text, 'DD-MM-YYYY HH:mm');
console.log(a); // Thu Jan 02 2020 00:10:00 GMT+0530
Then format the date in your desired format
var b = a.format('DD/MM/YYYY');
console.log(b); // 02/01/2020

Date(string) shows different date and time using toLocaleString

I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
See fiddle: https://jsfiddle.net/f1kLpfgd/
Javascript Date string constructing wrong date explains the wrong date with time zones. I have a different problem, as even minutes and seconds differ from my input. The solution using the new Date(1822, 0, 1, 0, 0, 0, 0) constructor does not work for me, as the result is 31.12.1821, 23:53:28.
Is it because the year is before 1901? But even 1899 works perfectly fine...
Update
For the formatting example custom VS toLocaleString, see updated fiddle: https://jsfiddle.net/f1kLpfgd/8/
If you don't want to use some library like date-fns , moment.js ...
To get the desired you could try like:
var dateString = "1822-01-01 00:00:00";
var d = new Date(dateString);
var formatted = d.getDate() +'.'+
(d.getMonth()+1) +'.'+
d.getFullYear() +', '+
dateString.substr(11);
console.log(formatted);
I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
Do not use the built-in parser for non-standard strings as whatever you get is implementation dependent and likely not what you expect in at least some hosts. In Safari, d will be an invalid date.
The format returned by toLocaleString is implementation dependent and varies between browsers. For me, new Date().toLocaleString() returns "9/21/2017, 9:48:49 AM", which is not consistent with the format typically used either in my locality or by users of the language I speak.
If you just want to reformat the string, see Reformat string containing date with Javascript.
If you want to know how to parse the string correctly, see Why does Date.parse
give incorrect results?
If you want to format a Date, see Where can I find documentation on formatting a date in JavaScript?

Date to epoch and vice versa - JavaScript

I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link
You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);
var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

Issue with javascript date object

I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)

Javascript convert "05/27 11:00pm" to date?

How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object?
Many different date formats can be converted to date objects just by passing them to the Date() constructor:
var date = new Date(datestring);
Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).
// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")
If the date formats you're receiving are consistent, you can fix them up this way:
var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
I'd use the Datejs library's parse method.
http://www.datejs.com/
I tried your example and it worked fine...
5/27 11:00pm
Wednesday, May 27, 2009 11:00:00 PM
I have used the Dojo time parser to do things like this:
Check it out:
http://api.dojotoolkit.org/jsdoc/HEAD/dojo.date.locale.parse
Not the cleanest, but works:
var strDate = '05/27 11:00pm';
var myDate = ConvertDate(strDate, '2009');
function ConvertDate(strWeirdDate, strYear)
{
strWeirdDate = strWeirdDate.replace(/ /, '/' + strYear + ' ');
return new Date(strWeirdDate);
}
Probably want to trim the string first as well.
Just another option, which I wrote:
DP_DateExtensions Library
It has a date/time parse method - pass in a mask and it'll validate the input and return a data object if they match.
Also supports date/time formatting, date math (add/subtract date parts), date compare, speciality date parsing, etc. It's liberally open sourced.

Categories

Resources