Related
I am trying to save a string in MongoDB as a date but having hard times for storing the right values.
In Mongoose schema data value is stored as Date, however, I pass the value to data as new Date("MM-dd-YYYY") but when I look up in the database the value is transformed to this format ISODate("YYYY-MM-dd-1T21:00:00Z")
The format wouldn't bother me if the date would be the same but as you notice the value in the database is one day earlier then the value which I want to be.
So instead of 2018-09-20 is 2018-08-19. My guess is that default UTC time is not the same or something like that but how can I set the correct UTC time?
Edit:
var mongoose = require('mongoose')
var dateformat =require('moment');
//Schema
var ReservationSchema = mongoose.Schema({
name : {
type:String,
required : true,
},
numberOfGuests : {
type : Number ,
required : true,}
,
email: {
type : String,
required:true,
},
phone: {
type : String,
required:true,
},
data:{
type:Date,
require:true,
},
timetables:{
type:String,
require:true,
},
furtherRequests: {
type : String,
}
});
var reservvar = module.exports = mongoose.model('Rezervari', ReservationSchema ,'Rezervari');
module.exports.createReservation = function (query,callback){
//query.data = dateformat.utc(query.data).format("MM-DD-YYYY")
reservvar.create(query,callback);
}
module.exports.getReservations = function (callback){
reservvar.find({},callback);
}
Index.js file :
app.get('/api/reservations',function(req,res) {
Rezervari.getReservations(function(err,reserv){
if(err){
throw err;
}
var changetime = reserv[1].data;
console.log(reserv[1].data)
changetime = dateformat.utc(changetime).format("MM-DD-YYYY") // this one returns the date in desired format but with wrong values as stored in db
console.log(changetime)
res.json(reserv);
});
});
app.post('/api/createrezervare', function (req,res) {
const reserv = req.body
const name = reserv.name
const numberofg = reserv.number
const phone = reserv.phone
const email = reserv.email
const data = reserv.date
const timetable = reserv.time
const furtreq = reserv.frequests
Rezervari.createReservation({name:name,numberOfGuests:numberofg,phone:phone,email:email,data:data,timetables:timetable,furtRequests:furtreq},function(err,reserv){
if(err){
throw err}
res.json({status:true})
})
})
You are inserting a Javascript Date Object from Node.js, and that same Date is being inserted in MongoDB, it's being inserted correctly.
I think you are confusing how dates are stored internally and how are they formatted when you print them.
When you check the content of your data in MongoDB it's just shown in that particular format, an ISO date. If you take a close look at the date shown you can see a Z a the end, Z means "zero hour offset" also known as "Zulu time" (UTC).
In Javascript when you create a Date object without setting the timezone, it's by default created in your system timezone. Also, Date objects are not stored with any format, nor in JS nor in MongoDB. In JS, dates are stored internally as time values (milliseconds since 1970-01-01).
Supposing we are in Japan, JST time (UTC+9):
const d = new Date("09-20-2018");
console.log(d.getTime()); // 1537369200000
console.log(d.toString()); // Thu Sep 20 2018 00:00:00 GMT+0900 (JST)
console.log(d.toISOString()); // 2018-09-19T15:00:00.000Z
First we are printing out the number of ms, after the Date including the timezone, and finally the ISO Date, almost same format that MongoDB uses to print dates in the Mongo shell (anyway, in UTC).
So, new Date("09-20-2018") is going to store the milliseconds until 09-20-2018 00:00 in Japan Time. Then, if you insert that object in MongoDB, internally it will store the correct date (I don't know internal details of MongoDB, but maybe it's storing the milliseconds as well).
If you check MongoDB you will see something like ISODate("2018-09-19T15:00:00Z").
I am trying to retrieve data using angularfire .I.e retrieve all data in an array from one timestamp to another timestamp.
var messageOfEachUser =firebase.database().ref().child("messages").child(data.key);
var currentTime = firebase.database.ServerValue.TIMESTAMP;
var query = messageOfEachUser.queryOrderedByChild("time").queryStartingAtValue(currentTime).queryEndingAtValue(lastSeenValueFromNode);
var listOfNewMessages = $firebaseArray(query);
console.log(listOfNewMessages);
Here in the above code connection to firebase. And querying data from a currenTime to lastSeenValueFromNode where lastSeenValueFromNode contains a timestamp when a user visited this node last time.
You cannot user firebase.database.ServerValue.TIMESTAMP in the way you are doing here. It is really just a marker value, that will be converted into the actual timestamp when your operation reaches the server.
Since you are using timestamps, you can simply use the local time as a rough estimate:
var currentTime = Date.now();
Alternatively, you can use Firebase's built-in latency detection value and get a value that is closer to ServerValue.TIMESTAMP:
var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var currentTime = Date.now() + offset;
});
I am using firebase for my chat application. In chat object I am adding time stamp using Firebase.ServerValue.TIMESTAMP method.
I need to show the message received time in my chat application using this Time stamp .
if it's current time i need to show the time only.It's have days difference i need to show the date and time or only date.
I used the following code for convert the Firebase time stamp but i not getting the actual time.
var timestamp = '1452488445471';
var myDate = new Date(timestamp*1000);
var formatedTime=myDate.toJSON();
Please suggest the solution for this issue
A Timestamp is an object:
timestamp = {
nanoseconds: 0,
seconds: 1562524200
}
console.log(new Date(timestamp.seconds*1000))
Firebase.ServerValue.TIMESTAMP is not actual timestamp it is constant that will be replaced with actual value in server if you have it set into some variable.
mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.on('value', function(snapshot){ console.log(snapshot.val()) })
//{startedAt: 1452508763895}
if you want to get server time then you can use following code
fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
var offsetVal = offset.val() || 0;
var serverTime = Date.now() + offsetVal;
});
inside Firebase Functions transform the timestamp like so:
timestampObj.toDate()
timestampObj.toMillis().toString()
documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
In fact, it only work to me when used
firebase.database.ServerValue.TIMESTAMP
With one 'database' more on namespace.
For those looking for the Firebase Firestore equivalent. It's
firebase.firestore.FieldValue.serverTimestamp()
e.g.
firebase.firestore().collection("cities").add({
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
Docs
I know the firebase give the timestamp in {seconds: '', and nanoseconds: ''}
for converting into date u have to only do:
take a firebase time in one var ex:- const date
and then date.toDate() => It returns the date.
For Firestore that is the new generation of database from Google, following code will simply help you through this problem.
var admin = require("firebase-admin");
var serviceAccount = require("../admin-sdk.json"); // auto-generated file from Google firebase.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
var db = admin.firestore();
console.log(admin.firestore.Timestamp.now().toDate());
Solution for newer versions of Firebase (after Jan 2016)
The proper way to attach a timestamp to a database update is to attach a placeholder value in your request. In the example below Firebase will replace the createdAt property with a timestamp:
firebaseRef = firebase.database().ref();
firebaseRef.set({
foo: "bar",
createdAt: firebase.database.ServerValue.TIMESTAMP
});
According to the documentation, the value firebase.database.ServerValue.TIMESTAMP is: "A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) by the Firebase Database servers."
Here is a safe method to convert a value from firebase Timestamp type to JS Date
in case the value is not Timestamp the method returns it as it is
Works for Angular 7/8/9
import firebase from 'firebase';
import Timestamp = firebase.firestore.Timestamp;
export function convertTimestampToDate(timestamp: Timestamp | any): Date | any {
return timestamp instanceof Timestamp
? new Timestamp(timestamp.seconds, timestamp.nanoseconds).toDate()
: timestamp;
}
Try this one,
var timestamp = firebase.firestore.FieldValue.serverTimestamp()
var timestamp2 = new Date(timestamp.toDate()).toUTCString()
Working with Firebase Firestone 18.0.1
(com.google.firebase.Timestamp)
val timestamp = (document.data["timestamp"] as Timestamp).toDate()
It is simple. Use that function to get server timestamp as milliseconds one time only:
var getServerTime = function( cb ) {
this.db.ref( '.info/serverTimeOffset' ).once( 'value', function( snap ) {
var offset = snap.val();
// Get server time by milliseconds
cb( new Date().getTime() + offset );
});
};
Now you can use it anywhere like that:
getServerTime( function( now ) {
console.log( now );
});
Why use this way?
According to latest Firebase documentation, you should convert your Firebase timestamp into milliseconds. So you can use estimatedServerTimeMs variable below:
var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var estimatedServerTimeMs = new Date().getTime() + offset;
});
While firebase.database.ServerValue.TIMESTAMP is much more accurate,
and preferable for most read/write operations, it can occasionally be
useful to estimate the client's clock skew with respect to the
Firebase Realtime Database's servers. You can attach a callback to the
location /.info/serverTimeOffset to obtain the value, in milliseconds,
that Firebase Realtime Database clients add to the local reported time
(epoch time in milliseconds) to estimate the server time. Note that
this offset's accuracy can be affected by networking latency, and so
is useful primarily for discovering large (> 1 second) discrepancies
in clock time.
https://firebase.google.com/docs/database/web/offline-capabilities
new Date(timestamp.toDate()).toUTCString()
import firebaseAPP from 'firebase/app';
public Date2firestoreTime(fromDate: Date) {
return firebaseAPP.firestore.Timestamp.fromDate(fromDate).toMillis()
}
public firestoreTime2Date(millisecDate: number) {
return firebaseAPP.firestore.Timestamp.fromMillis(millisecDate).toDate()
}
//usage:
let FSdatenow = this.Date2firestoreTime(new Date())
console.log('now to firestore TimeStamp', FSdatenow)
let JSdatenow = this.firestoreTime2Date(FSdatenow)
console.log('firestore TimeStamp to Date Obj', JSdatenow)
var date = new Date((1578316263249));//data[k].timestamp
console.log(date);
Iterating through this is the precise code that worked for me.
querySnapshot.docs.forEach((e) => {
var readableDate = e.data().date.toDate();
console.log(readableDate);
}
For me it works when the timeStamp is an integer rather than a string:
var timestamp = '1452488445471';
var myDate = new Date(parseInt(timestamp));
myDate.toDateString()
I converted to this format
let timestamp = '1452488445471';
let newDate = new Date(timestamp * 1000)
let Hours = newDate.getHours()
let Minutes = newDate.getMinutes()
const HourComplete = Hours + ':' + Minutes
let formatedTime = HourComplete
console.log(formatedTime)
let jsDate = new Date(date.seconds * 1000 + date.nanoseconds / 1000000);
You might have to specify the type to use .toDate() like this;
import { Timestamp } from "firebase/firestore";
...
(dateVariable as unknown as Timestamp).toDate()
This was .toDate() works as intended.
First Of All Firebase.ServerValue.TIMESTAMP is not working anymore for me.
So for adding timestamp you have to use Firebase.database.ServerValue.TIMESTAMP
And the timestamp is in long millisecond format.To convert millisecond to simple dateformat .
Ex- dd/MM/yy HH:mm:ss
You can use the following code in java:
To get the timestamp value in string from the firebase database
String x = dataSnapshot.getValue (String.class);
The data is in string now. You can convert the string to long
long milliSeconds= Long.parseLong(x);
Then create SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Now convert your millisecond timestamp to ur sdf format
String dateAsString = sdf.format (milliSeconds);
After that you can parse it to ur Date variable
date = sdf.parse (dateAsString);
This code is work for me
<script src="https://www.gstatic.com/firebasejs/4.5.1/firebase.js"></script>
<script>
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
var reff = firebase.database().ref('message');
reff.on('value',haveData, haveerr);
function haveData(datahave){
var existval= datahave.val();
var chabi=Object.keys(existval);
for(var d2=0;d2< chabi.length;d2++){
var r=chabi[d2];
var exitval=existval[r].Message;
var exitval1=existval[r].Name;
var exit=existval[r].Email;
var exitval2=existval[r].Subject;
var timestamp=existval[r].timestamp;
var sdate=new Date(timestamp);
var Year=sdate.getFullYear();
var month=sdate.getMonth()+1;
var day=sdate.getDate();
var hh=sdate.getHours();
var mm=sdate.getMinutes();
var ss=sdate.getSeconds();
}
}
function haveerr(e){
console.log(e);
}
</script>
Firebase.ServerValue.TIMESTAMP is the same as new Date().getTime().
Convert it:
var timestamp = '1452488445471';
var myDate = new Date(timestamp).getTime();
I have the following data:
var currentTime: 2013-07-11 15:55:36+00:00
var currentTimezone: Africa/Asmera
I need a way to convert the currentTime in UTC to a new time based on currentTimezone.
I've looked into Timezone.js and I'm having trouble implementing it (the directions on the site are a little ambiguous)
The code for the function I'm intending on using is included. Thanks :)
<script>
$("#storeTime").click(function(){
storeCurrentTime();
})
$("#getTime").click(function(){
retrieveTime();
})
$("#storeTimezone").click(function(){
var yourTimezone = $('#timezone-select').find(":selected").text();
tz = yourTimezone.toString();
storeCurrentTimezone(tz);
})
$("#convertTime").click(function(){
//get the most recent UTC time, clean it up
var currentTime = $('#RetrievedTime').html();
currentTime = currentTime.split(": ")[1];
$('#convertedTime').html("Converted Time: " + currentTime);
//get the saved timezone
var currentTimezone = $('#storedTimezone').html();
})
</script>
You're going to need to know the timezone offset, so some sort of dictionary with strings to numbers.
// assuming your dictionary says 3 hours is the difference just for example.
var timezoneDiff = 3;
Then you can just make a new time like this
// Assuming you have the proper Date string format in your date field.
var currentDate = new Date(currentTime);
// Then just simply make a new date.
var newDate = new Date(currentDate.getTime() + 60 * 1000 * timezoneDiff);
Update
I've written a javascript helper for this which you can find at:
http://heuuuuth.com/projects/OlsonTZConverter.js
I pulled the timezone data from the wikipedia page https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Usage is as follows once included the script.
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera");
or if there is Daylight Savings in effect:
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera",true);
These will throw if you pass an invalid timezone, but you can check if a timezone is valid with:
var isValid = OlsonTZConverter.Contains("Africa/Asmera");
or just look at the entire dictionary with:
var tzDict = OlsonTZConverter.ListAllTimezones();
Hope this maybe saves someone some time sometime :).
My date objects in JavaScript are always represented by UTC +2 because of where I am located. Hence like this
Mon Sep 28 10:00:00 UTC+0200 2009
Problem is doing a JSON.stringify converts the above date to
2009-09-28T08:00:00Z (notice 2 hours missing i.e. 8 instead of 10)
What I need is for the date and time to be honoured but it's not, hence it should be
2009-09-28T10:00:00Z (this is how it should be)
Basically I use this:
var jsonData = JSON.stringify(jsonObject);
I tried passing a replacer parameter (second parameter on stringify) but the problem is that the value has already been processed.
I also tried using toString() and toUTCString() on the date object, but these don't give me what I want either..
Can anyone help me?
Recently I have run into the same issue. And it was resolved using the following code:
x = new Date();
let hoursDiff = x.getHours() - x.getTimezoneOffset() / 60;
let minutesDiff = (x.getHours() - x.getTimezoneOffset()) % 60;
x.setHours(hoursDiff);
x.setMinutes(minutesDiff);
JSON uses the Date.prototype.toISOString function which does not represent local time -- it represents time in unmodified UTC -- if you look at your date output you can see you're at UTC+2 hours, which is why the JSON string changes by two hours, but if this allows the same time to be represented correctly across multiple time zones.
date.toJSON() prints the UTC-Date into a String formatted (So adds the offset with it when converts it to JSON format).
date = new Date();
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
Just for the record, remember that the last "Z" in "2009-09-28T08:00:00Z" means that the time is indeed in UTC.
See http://en.wikipedia.org/wiki/ISO_8601 for details.
Out-of-the-box solution to force JSON.stringify ignore timezones:
Pure javascript (based on Anatoliy answer):
// Before: JSON.stringify apply timezone offset
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
// After: JSON.stringify keeps date as-is!
Date.prototype.toJSON = function(){
const hoursDiff = this.getHours() - this.getTimezoneOffset() / 60;
this.setHours(hoursDiff);
return this.toISOString();
};
string = JSON.stringify(date);
console.log(string);
Using moment + moment-timezone libraries:
const date = new Date();
let string = JSON.stringify(date);
console.log(string);
Date.prototype.toJSON = function(){
return moment(this).format("YYYY-MM-DDTHH:mm:ss:ms");;
};
string = JSON.stringify(date);
console.log(string);
<html>
<header>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.min.js"></script>
</header>
</html>
Here is another answer (and personally I think it's more appropriate)
var currentDate = new Date();
currentDate = JSON.stringify(currentDate);
// Now currentDate is in a different format... oh gosh what do we do...
currentDate = new Date(JSON.parse(currentDate));
// Now currentDate is back to its original form :)
you can use moment.js to format with local time:
Date.prototype.toISOString = function () {
return moment(this).format("YYYY-MM-DDTHH:mm:ss");
};
I'm a little late but you can always overwrite the toJson function in case of a Date using Prototype like so:
Date.prototype.toJSON = function(){
return Util.getDateTimeString(this);
};
In my case, Util.getDateTimeString(this) return a string like this: "2017-01-19T00:00:00Z"
I run into this a bit working with legacy stuff where they only work on east coast US and don't store dates in UTC, it's all EST. I have to filter on the dates based on user input in the browser so must pass the date in local time in JSON format.
Just to elaborate on this solution already posted - this is what I use:
// Could be picked by user in date picker - local JS date
date = new Date();
// Create new Date from milliseconds of user input date (date.getTime() returns milliseconds)
// Subtract milliseconds that will be offset by toJSON before calling it
new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
So my understanding is this will go ahead and subtract time (in milliseconds (hence 60000) from the starting date based on the timezone offset (returns minutes) - in anticipation for the addition of time toJSON() is going to add.
JavaScript normally convert local timezone to UTC .
date = new Date();
date.setMinutes(date.getMinutes()-date.getTimezoneOffset())
JSON.stringify(date)
Usually you want dates to be presented to each user in his own local time-
that is why we use GMT (UTC).
Use Date.parse(jsondatestring) to get the local time string,
unless you want your local time shown to each visitor.
In that case, use Anatoly's method.
Got around this issue by using the moment.js library (the non-timezone version).
var newMinDate = moment(datePicker.selectedDates[0]);
var newMaxDate = moment(datePicker.selectedDates[1]);
// Define the data to ask the server for
var dataToGet = {"ArduinoDeviceIdentifier":"Temperatures",
"StartDate":newMinDate.format('YYYY-MM-DD HH:mm'),
"EndDate":newMaxDate.format('YYYY-MM-DD HH:mm')
};
alert(JSON.stringify(dataToGet));
I was using the flatpickr.min.js library. The time of the resulting JSON object created matches the local time provided but the date picker.
Here is something really neat and simple (atleast I believe so :)) and requires no manipulation of date to be cloned or overloading any of browser's native functions like toJSON (reference: How to JSON stringify a javascript Date and preserve timezone, courtsy Shawson)
Pass a replacer function to JSON.stringify that stringifies stuff to your heart's content!!! This way you don't have to do hour and minute diffs or any other manipulations.
I have put in console.logs to see intermediate results so it is clear what is going on and how recursion is working. That reveals something worthy of notice: value param to replacer is already converted to ISO date format :). Use this[key] to work with original data.
var replacer = function(key, value)
{
var returnVal = value;
if(this[key] instanceof Date)
{
console.log("replacer called with key - ", key, " value - ", value, this[key]);
returnVal = this[key].toString();
/* Above line does not strictly speaking clone the date as in the cloned object
* it is a string in same format as the original but not a Date object. I tried
* multiple things but was unable to cause a Date object being created in the
* clone.
* Please Heeeeelp someone here!
returnVal = new Date(JSON.parse(JSON.stringify(this[key]))); //OR
returnVal = new Date(this[key]); //OR
returnVal = this[key]; //careful, returning original obj so may have potential side effect
*/
}
console.log("returning value: ", returnVal);
/* if undefined is returned, the key is not at all added to the new object(i.e. clone),
* so return null. null !== undefined but both are falsy and can be used as such*/
return this[key] === undefined ? null : returnVal;
};
ab = {prop1: "p1", prop2: [1, "str2", {p1: "p1inner", p2: undefined, p3: null, p4date: new Date()}]};
var abstr = JSON.stringify(ab, replacer);
var abcloned = JSON.parse(abstr);
console.log("ab is: ", ab);
console.log("abcloned is: ", abcloned);
/* abcloned is:
* {
"prop1": "p1",
"prop2": [
1,
"str2",
{
"p1": "p1inner",
"p2": null,
"p3": null,
"p4date": "Tue Jun 11 2019 18:47:50 GMT+0530 (India Standard Time)"
}
]
}
Note p4date is string not Date object but format and timezone are completely preserved.
*/
I ran into the same problem.
The way I resolvet it was:
var currentTime = new Date();
Console.log(currentTime); //Return: Wed Sep 15 13:52:09 GMT-05:00 2021
Console.log(JSON.stringify(currentTime)); //Return: "2021-09-15T18:52:09.891Z"
var currentTimeFixed = new Date(currentTime.setHours(currentTime.getHours() - (currentTime.getUTCHours() - currentTime.getHours())));
Console.log(JSON.stringify(currentTimeFixed)); //Return: "2021-09-15T13:52:09.891Z"
I wrote the following code blog where it makes service calls.. it will try to serializable the json in every post submission, it will format to local date it again.
protected async post(endPoint: string, data, panelName?: string, hasSuccessMessage: boolean = false): Promise<Observable<any>> {
const options = this.InitHeader(true);
const url: string = this._baseUrl + endPoint;
Date.prototype.toJSON = function () {
return moment(this).format("YYYY-MM-DDThh:mm:00.000Z");;
};
return await this._http.post(url, data, options).pipe(map(response => {
return this.Map<any>(response, null);
}));
}
All boils down to if your server backend is timezone-agnostic or not.
If it is not, then you need to assume that timezone of server is the same as client, or transfer information about client's timezone and include that also into calculations.
a PostgreSQL backend based example:
select '2009-09-28T08:00:00Z'::timestamp -> '2009-09-28 08:00:00' (wrong for 10am)
select '2009-09-28T08:00:00Z'::timestamptz -> '2009-09-28 10:00:00+02'
select '2009-09-28T08:00:00Z'::timestamptz::timestamp -> '2009-09-28 10:00:00'
The last one is probably what you want to use in database, if you are not willing properly implement timezone logic.
Instead of toJSON, you can use format function which always gives the correct date and time + GMT
This is the most robust display option. It takes a string of tokens
and replaces them with their corresponding values.
I tried this in angular 8 :
create Model :
export class Model { YourDate: string | Date; }
in your component
model : Model;
model.YourDate = new Date();
send Date to your API for saving
When loading your data from API you will make this :
model.YourDate = new Date(model.YourDate+"Z");
you will get your date correctly with your time zone.
In this case I think you need transform the date to UNIX timestamp
timestamp = testDate.getTime();
strJson = JSON.stringify(timestamp);
After that you can re use it to create a date object and format it. Example with javascript and toLocaleDateString ( https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleDateString )
newDateObject = new Date(JSON.parse(strJson));
newDateObject = newDateObject.toLocalDateStrin([
"fr-FR",
]);
If you use stringify to use AJAX, now it's not useful. You just need to send timestamp and get it in your script:
$newDateObject = new \DateTime();
$newDateObject->setTimestamp(round($timestamp/1000));
Be aware that getTime() will return a time in milliseconds and the PHP function setTimestamp take time in seconds. It's why you need to divide by 1000 and round.
In Angular place the following in index.js script section:
setTimeout(function (){
Date.prototype.toJSON = function(){
return new Date(this).toLocaleDateString("en-US") + " "+new Date(this).toLocaleTimeString();
}},1000);