Why date is mismatch in JavaScript while conversion? - javascript

Why date is mismatch in javascript .I am getting this millisecond “-2208988800000” .I converted this using moment like this
moment(new Date(-2208988800000).toUTCString()).format('DD-MMM-YYYY')
Which give output “01-Jan-1900"” (which is correct)
Now I try to get again same long value or millisecond
moment(new Date("01-Jan-1900")).format('x')
"-2209008070000"
Why is mismatch in value ? "-2209008070000" and "-2208988800000" is not same

new Date("01-Jan-1900") is not something that works in every browser. Firefox for example outputs Invalid Date. The Date constructor has lots of quirks, and it's exactly why you should use a library like Moment.js to parse date and time strings.
Refer to the MDN documentation on Date and new Date(dateString) for additional details.

I think you are losing hours while converting to DD-MMM-YYYY
console.log(moment(new Date(-2208988800000).toUTCString()).format('DD-MMM-YYYY HH:mm:ss'))
//output of above line is input to below.
console.log(moment.parseZone(new Date("31-Dec-1899 19:00:00")).format('x'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>

Related

javascript "date.getFullYear()" is returning 3991 [duplicate]

I have tried to get date and time from firebase timestamp as follows:
Date date=new Date(timestamp*1000);
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sfd.format(date);
but I'm getting results like:
:02-02-48450 04:21:54
:06-02-48450 10:09:45
:07-02-48450 00:48:35
as you can see the year is not as we live.
So, please help me to fix this.
Your timestamp 1466769937914 equals to 2016-06-24 12:05:37 UTC. The problem is that you are multiplying the timestamp by 1000. But your timestamp already holds a value in milliseconds not in seconds (this false assumption is most likely the reason you have the multiplication). In result you get 1466769937914000 which converted equals to 48450-02-01 21:51:54 UTC. So technically speaking all works fine and results you are getting are correct. All you need to fix is your input data and the solution is quite simple - just remove the multiplication:
SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sfd.format(new Date(timestamp));
If you are looking to get a Date instance from Timestamp
If you need to get just the Date object from Timestamp, the Timestamp instance comes with a toDate() method that returns a Date instance.
For clarity:
Date javaDate = firebaseTimestampObject.toDate()
According to Firebase documentation, the types that are available JSON are:
String
Long
Double
Boolean
Map<String, Object>
List<Object>
Quoting another Stack Overflow post, I suggest you use JSON date string format yyyy-MM-dd'T'HH:mm:ss.SSSZ instead of epoch timestamp.
Comparing 1335205543511 to 2012-04-23T18:25:43.511Z, you can noticed that:
It's human readable but also succinct
It sorts correctly
It includes fractional seconds, which can help re-establish chronology
It conforms to ISO 8601
ISO 8601 has been well-established internationally for more than a decade and is endorsed by W3C, RFC3339, and XKCD
The .toDate() method should be all you need
You might like the docs here
As an added bonus, you might want very highly human readable output
Date only options
.toDate().toDateString()
.toDate().toLocaleDateString()
Time only options
.toDate().toTimeString()
.toDate().toLocaleTimeString()
Objects
However, if you are receiving an object you might do something like this
{JSON.stringify(createdAt.toDate()).replace(/['"]+/g, '')}
Converting the object into a string then replacing the quotes around the string.
firebase time is basically combination of seconds and nano seconds
time={
seconds:1612974698,
nanoseconds:786000000
}
total_miliseconds=(time.seconds+(time.nanoseconds)*0.00000001)*1000. // 1 nanosecond=1e-9 means 0.00000001
new Date(total_miliseconds)
String time=dataSnapshot.child("timeStamp").getValue().toString();
Long t=Long.parseLong(time);
Date myDate = new Date(t*1000);
Result
Fri May 11 05:37:58 GMT+06:30
For date, you can use this code :
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", calendar).toString();
For time :
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
String date = DateFormat.format("hh:mm", calendar).toString();
I think its bit late but easiest way is just:
(new Date(timestamp.toDate())).toDateString()
Within the Date() where you put your timestamp add
.toDate()
to the timestamp variable as #jasonleonhard said. Maybe just an example
new Date(timestamp.toDate())

how to get only time from date in ISO formate

How to extract only time from the date which is present in ISO format?
I tried this:
var d = new Date('1970-01-15T03:32:12.000Z'); //ISO-8601 formatted date returned from server
console.log(d.getTime());// 1222332000
Expected op is : 03:32:12
Since your server returns an ISO-8601 formatted date which has a predefined format, you can convert it to ISO string using toISOString() and then get the substring of the time value:
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(d.toISOString().substr(11,8));
Date.getTime() returns the time in UNIX epoch format.
https://en.wikipedia.org/wiki/Unix_time
To access only the parameters you are interested in, you can use Date.getMinutes(), Date.getMinutes(), etc. See docs on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Note: Do not forget to spend one thought on time zones when you work with Date
's time, especially when your app runs in different regions.
You have to manually build the time string using Date.prototype methods: getHours, getMinutes and getSeconds
Or use moment.js library.
Date.getTime() gives you the unix timestamp, which is the number of seconds since january 1st 1970;
The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time.
from MDN
You need to format the date yourself, either by concatenating the output of the Date.getHours(), Date.getMinutes() and Date.getSeconds() methods, or by using one of the predefined formatting functions, like Date.toTimeString(). Checkout the docs to pick your choice.
You can use getHours(),getMinutes() and getSecondes(). Then you can use it with strings or objects.
Try the following:
d.toTimeString().split(' ')[0]
You can use moment.js to parse whatever format you like.
If you think moment.js is too big, there's another library call dayjs. The same fashion API but just 2KB. (Unfortunately, you can't do UTC time with dayjs yet.)
Update: Thanks kun for notifying the updates. You can now use UTC with dayjs plugin since v1.8.9.
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(moment(d).utc().format('HH:mm:ss'));
dayjs.extend(dayjs_plugin_utc)
console.log(dayjs(d).utc().format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/plugin/utc.js"></script>

Weird ISO formatted Datestring to Javascript Date

I've got a Datestring like this one: 20171010T022902.000Z and I need to create Javascript Date from this string. new Date('20171010T022902.000Z') would return Invalid Date.
I saw that it's possible to use moment.js for this purpose but I am not sure how I would specify the according format for my given example. I found this example from another thread:
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');
var jsDate = momentDate.toDate();
Question:
How can I create a JavaScript date from a given Datestring in this format: 20171010T022902.000Z (using moment)?
Your input (20171010T022902.000Z) matches known ISO 8601 so you can simply use moment(String) parsing method. In the Supported ISO 8601 strings section of the docs you will find:
20130208T080910.123 # Short date and time up to ms
Then you can use toDate() method
To get a copy of the native Date object that Moment.js wraps
Your code could be like the following
var m = moment('20171010T022902.000Z');
console.log( m.format() );
console.log( m.toDate() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Note that this code does not shows Deprecation Warning (cited in Bergi's comment) because you input is in ISO 8601 known format. See this guide to know more about this warning.
Moreover "By default, moment parses and displays in local time" as stated here so format() will show the local value for your UTC input (20171010T022902.000Z ends with Z). See moment.utc(), utc() and Local vs UTC vs Offset guide to learn more about moment UTC mode.
I think you can do this without moment.js,.
Basically extract the parts you need using regex's capture groups, and then re-arrange into a correct format for new Date to work with.
var dtstr = '20171010T022902.000Z';
var dt = new Date(
dtstr.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(\.\d{3}Z)$/,
"$1-$2-$3T$4:$5:$6$7"));
console.log(dt);
console.log(dt.toString());
If you are using moment.js anyway, this should work ->
var dt = moment("20171010T022902.000Z", "YYYYMMDDTHHmmss.SSSSZ");
console.log(dt.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

Javascript Date conversion Invalid Date

I was looking for this very specific conversion which I couldnt find anywhere
var d = new Date("2014-12-25T18:30:00+0100");
console.log(d.toString());
the console.log returns an "Invalid Date"
The DateString is returned by the Facebook GraphAPI.
What am I doing wrong? can anyone help?
Thanks in advance
EDIT:
Now that I fixed the API my output is kind of consfusing:
I tried splitting up the String
d.getDay()+'.'+d.getMonth()+'.'+d.getYear()+' '+d.getHours()+':'+d.getMinutes();
it outputs
4.11.114 18:30
why?!
Instead of doing those complicated date functions
d.getDate()+'.'+d.getMonth()+'.'+d.getYear()+' '+d.getHours()+':'+d.getMinutes();
Do yourself a favour and include http://momentjs.com/ in your project. You can then simply take the date from the facebook api and format it with
moment("2014-12-25T18:30:00+0100").format("/* date format */");
See here for formating
SIDENOTE
When formating dates in plain javascript, you will have to add 1 month to your month - january is 0, that's why you get 4.11... instead of 4.12...
Change getYear() to getFullYear()
d.getDay()+'.'+d.getMonth()+'.'+d.getFullYear()+' '+d.getHours()+':'+d.getMinutes();

Date (dateString) returning invalid date in Firefox

The page works fine in Chrome, but I have this one minor error in Firefox and a different problem in IE. Assistance with either of these issues is greatly appreciated. Since I've been stumped in the Firefox error the longest, I'll start with that one:
Here's the code: http://truxmapper.appspot.com/sched.html
The date picker selects a date using the format "07-08-2010 23:28". Now, I need to pass this time as a parameter to my servlet, which is expecting the time represented as a long. This is not a problem in Chrome. The Date object accepts a string in the format given above, but when I try to use getTime() on a date instantiated with a string in Firefox, it returns NaN. So what I've done in the on the page I linked to is a little handling asking the user to re-enter the dates if its read as NaN. This obviously isn't even a band-aid solution since even if you re-enter the date its still going to read NaN. I need to know why the Date function wont instantiate using the string you see in the input text field in Firefox.
In IE, for some reason its telling me that sTime is undefined.
That date format is ambiguous. Try it as yyyy-mm-dd instead of mm-dd-yyyy or dd-mm-yyyy.
Try
new Date(Date(dateString)).getTime()
(feels like an ugly workaround...)
Edit: This will produce wrong result.
The date format used in Javascript should be of the form YYYY MM DD HH:mm:ss. You can convert the format into this form with
// dateString = "07-08-2010 23:28";
dateString = dateString.replace(/(\d+) (\d+) (\d+)/, '$3-$1-$2');
But as mentioned in the comment, there is no standard Date format used by Javascript before the ECMAScript 5 standard. It is better to parse the dateString directly:
m = dateString.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/)
date = new Date(+m[3], m[1]-1, +m[2], +m[4], +m[5]); // Note: January = 0.

Categories