Database timestamps returning intriguing values - javascript

I am using javascript to read the values of a JSON object that is returned after a GET call.
The database that provides the values is making a timestamp like this:
26-04-2019 17:22:25;
into:
1556233200000....
How can I fix this? I have no access to the database.

This is no intriguing value. It is in epoch time.
You can simply convert it back to an ISO string by using declaring JavaScript's Date instance.
const dateValue = new Date(1556233200000);
console.log(dateValue);

That number (1556233200000) is the number of milliseconds since January 1, 1970 (1/1/1970).
More information about JavaScript date is available here: Date - JavaScript MDN.

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())

Mongodb date value to javascript string how to convert?

I logged out the value stored in one of the documents(or notes in my case) in the date key, like this
console.log(notes[0].date)
The output that I got was
and when methods like getDate() or toDateString() didn't work, what should i be doing?
You will need to convert it into a javascript date object using new Date("your mongodb date string");
See: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date for more infomation
If your dates are stored using the date data type you should manipulate them as data object in your code.
If your dates are not stored using the date data type you should migrate your data to store the date as date data type rather than string.
You then format the date, using the user’s LOCALE, only when you present it to the user.

new Date() returns relative time and not UTC time

When I go to my browser development tools and write new Date() in the console, it gives me the following
Mon Dec 18 2017 17:11:29 GMT+0200
I thought it suppose to return the UTC time.
The issue is that I have a server on AWS which writes UTC time to a DB. it writes it as a string and on the client side I do the following
const updatedMilliAgo = new Date() - new Date(timeStrFromDb);
For some reason the diff is two hours even due I check it right after the write in the server.
What am I doing wrong here?
When you use new Date(), you are constructing a Date object using the current value of the system clock where the code is executing. The Date object internally stores only a number of milliseconds since 1970-01-01T00:00:00Z (without consideration of leap seconds). In other words, Date objects are always representing the UTC time.
However - there are many functions and parameters on the Date object that work in local time. For example, when you call .toString() on a Date object, the computer's local time zone is applied to the internal UTC-based value, in order to generate a string that reflects local time.
In the case of console.log - a standard object like Date cannot be directly logged. Instead, most implementations will log a string value. How that value is created is entirely implementation specific, and not defined by the ECMAScript specification. Many implementations will return the same local-time based value that .toString() returns. Some (FireFox, for example) will return the same UTC based value that .toISOString() returns. It would be reasonable for an implementation to return the actual number of milliseconds stored (.valueOf()), or some other representation. If you need consistency, don't just log the Date object. Instead, log the output of one of its functions that returns a string or a number.
You also asked about subtracting two date objects. That will implicitly call .valueOf() on each object, subtracting their UTC-based internal values and giving you the number of milliseconds between them. The most likely problem you are encountering is with how you construct the second Date object. You didn't give an example of what timeStrFromDb consists of, but understand that how that string is formatted directly relates to how the Date object is constructed. If you aren't using a standardized format, or you aren't clear on whether the value is based on UTC or a specific offset from UTC, your string may be parsed differently than you expect.
Try to use
var d = new Date();
var n = d.toUTCString();
console.log(n)
I am late, but I didn't find the answer and I had to fight for hours vs the code... finally my solution was as simple as that:
TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of("UTC"));
timeZone.setDefault(timeZone);
When you set the default timezone, all dates you create will be in that ZoneId that you specify.
I hope to help to someone.

Passing Date Object With Ajaxpro

I pass an javascript object from client-side to server-side function with Ajaxpro.
In server-side date variables comes inside object are looks like below. What does it mean? How can i parse it to formatted date?
"/Date(1280381400000)/"
The number could be number of milliseconds since 1/1/1970 midnight. You need to construct the date object by passing this milliseconds and then format it.

Converting json results to a date [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to format a JSON date?
I have the following result from a $getJSON call from JavaScript. How do I convert the start property to a proper date in JavaScript?
[
{"id":1,"start":"/Date(1238540400000)/"},
{"id":2,"start":"/Date(1238626800000)/"}
]
Thanks!
You need to extract the number from the string, and pass it into the Date constructor:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
I use this:
function parseJsonDate(jsonDateString){
return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
Update 2018:
This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.
2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object
using dateObject.toISOString()
1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object
using dateObject.getTime()
If you use jQuery
In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.
You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.
It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).
Anyway. Head over to blog post to get the code.
http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html
If that number represents milliseconds, use the Date's constructor :
var myDate = new Date(1238540400000);

Categories