I have something like /Date(1370001284000+0200)/ as timestamp. I guess it is a unix date, isn't it? How can I convert this to a date like this: 31.05.2013 13:54:44
I tried THIS converter for 1370001284 and it gives the right date. So it is in seconds.
But I still get the wrong date for:
var substring = unix_timestamp.replace("/Date(", "");
substring = substring.replace("000+0200)/", "");
var date = new Date();
date.setSeconds(substring);
return date;
Note my use of t.format comes from using Moment.js, it is not part of JavaScript's standard Date prototype.
A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.
The presence of the +0200 means the numeric string is not a Unix timestamp as it contains timezone adjustment information. You need to handle that separately.
If your timestamp string is in milliseconds, then you can use the milliseconds constructor and Moment.js to format the date into a string:
var t = new Date( 1370001284000 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
If your timestamp string is in seconds, then use setSeconds:
var t = new Date();
t.setSeconds( 1370001284 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
Looks like you might want the ISO format so that you can retain the timezone.
var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Without moment.js:
var time_to_show = 1509968436; // unix timestamp in seconds
var t = new Date(time_to_show * 1000);
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);
document.write(formatted);
The /Date(ms + timezone)/ is a ASP.NET syntax for JSON dates. You might want to use a library like momentjs for parsing such dates. It would come in handy if you need to manipulate or print the dates any time later.
If using react:
import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';
then:
<td><Moment unix>{1370001284}</Moment></td>
Import moment js:
var fulldate = new Date(1370001284000);
var converted_date = moment(fulldate).format(");
if you're using React I found 'react-moment' library more easy to handle for Front-End related tasks, just import <Moment> component and add unix prop:
import Moment from 'react-moment'
// get date variable
const {date} = this.props
<Moment unix>{date}</Moment>
I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:
const today = moment(1557697070824.94).toObject();
You should obtain an object with this properties:
today: {
date: 15,
hours: 2,
milliseconds: 207,
minutes: 31,
months: 4
seconds: 22,
years: 2019
}
It is very useful when you have to calculate dates.
for people as dumb as myself, my date was in linux epoch
but it was a string instead of an integer, and that's why i was getting
RangeError: Date value out of bounds
so if you are getting the epoch from an api, parseInt it first
var dateTime = new Date(parseInt(1370001284000));
dateTime.toISOString();
Related
I am trying to convert the below date to a javascript Date() object. When I get it back from the server, it is a Timestamp object,
Screenshot from Firebase Firestore console:
When I try the following on a list of objects returned from firestore:
list.forEach(a => {
var d = a.record.dateCreated;
console.log(d, new Date(d), Date(d))
})
I get this output:
Clearly the Timestamps are all different, and are not all the same date of Sept 09, 2018 (which happens to be today). I'm also not sure why new Date(Timestamp) results in an invalid date. I'm a bit of a JS newbie, am I doing something wrong with the dates or timestamps?
The constructor for a JavaScript's Date doesn't know anything about Firestore's Timestamp objects — it doesn't know what to do with them.
If you want to convert a Timestamp to a Date, use the toDate() method on the Timestamp.
You can use toDate() function along with toDateString() to display the date part alone.
const date = dateCreated.toDate().toDateString()
//Example: Friday Nov 27 2017
Suppose you want only the time part then use the toLocaleTimeString()
const time = dateCreated.toDate().toLocaleTimeString('en-US')
//Example: 01:10:18 AM, the locale part 'en-US' is optional
You can use Timestamp.fromDate and .toDate for converting back and forth.
// Date to Timestamp
const t = firebase.firestore.Timestamp.fromDate(new Date());
// Timestamp to Date
const d = t.toDate();
How to convert Unix timestamp to JavaScript Date object.
var myDate = a.record.dateCreated;
new Date(myDate._seconds * 1000); // access the '_seconds' attribute within the timestamp object
Please use toDate() method and then convert it into the format using angular pipe like this -
{{ row.orderDate.toDate() | date: 'dd MMM hh:mm' }}
apart from other answers you can do it like this as well
//date from firebase is represented as
let time = {
seconds: 1613748319,
nanoseconds: 47688698687,
}
const fireBaseTime = new Date(
time.seconds * 1000 + time.nanoseconds / 1000000,
);
const date = fireBaseTime.toDateString();
const atTime = fireBaseTime.toLocaleTimeString();
console.log(date, atTime);
At last, I could get what I need. This returns date as 08/04/2020
new Date(firebase.firestore.Timestamp.now().seconds*1000).toLocaleDateString()
const timeStampDate = record.createdAt;
const dateInMillis = timeStampDate._seconds * 1000
var date = new Date(dateInMillis).toDateString() + ' at ' + new Date(dateInMillis).toLocaleTimeString()
OutPut Example: Sat 11 Jul 2020 at 21:21:10
This might help:
new Date(firebaseDate._seconds * 1000).toUTCString()
A simple way is to convert firestore timestamp to epoch timestamp is by using toMillis() method on firestore timestamp.
For example:
You have a firestore timestamp
created_on : Timestamp { _seconds: 1622885490, _nanoseconds: 374000000 }
let epochTimestamp = created_on.toMillis()
//epochTimestamp = 1621081015081
//Now this timestamp can be used as usual javascript timestamp which is easy to manipulate.
let date = new Date(epochTimestamp) //date = Sat May 15 2021 17:46:55 GMT+0530 (India Standard Time)
The timestamp object you get from firestore has a toDate() method you can use.
list.forEach(a => {
var d = a.record.dateCreated;
console.log(d.toDate())
})
Here's a quote from firebase docs about the toDate() method
Convert a Timestamp to a JavaScript Date object. This conversion
causes a loss of precision since Date objects only support millisecond
precision.
Returns Date JavaScript Date object representing the same point in
time as this Timestamp, with millisecond precision.
https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#todate
This works for me.
new Date(firebaseDate.toDate())
This works for me
let val = firebase.timestamp // as received from the database, the timestamp always comes in an object similar to this - {_nanoseconds: 488484, _seconds: 1635367}
(new Date( (val.time._seconds + val.time._nanoseconds * 10 ** -9) * 1000)).toString().substring(17, 21)
Lots of answer here, but as a rookie I found most of them confusing.
So for rookies like me, here is a simple explanation of how to convert a Firestore date/Timestamp to a Javascript Date() and why you need to.
Why convert?
Firestore stores Dates as a Timestamp object. This is not the same as a Javascript Date() object.
This was confusing to me because if you send a Date() object to Firestore, and then retrieve it, it will hand you back a Timestamp object. Like if you hand Firestore a dollar, it will hand you back 4 quarters. It is the same amount of money (or same date), but if you were expecting paper, and got metal, you would be confused.
How to convert
Luckily the Timestamp object has functions built into do give you a Javascript Date object: toDate
Note: Remember, toDate looks like the Javascript toLocaleDateString() or toDateString() but it is not. A JS Date() object and Firestore Timestamp object are not the same so don't make my rookie mistake of trying to use functions from one, on the other.
To convert a Firestore Timestamp into a Javascript date, just call .toDate() on the Timestamp.
//get the document from Firestore
let fireStoreTimestamp = doc.data().nameOfYourDateField;
let javascriptDate = fireStoreTimestamp.toDate();
You can use the dayjs library to convert firebase firestore timestamp seconds to your local time.
newDate = dayjs.unix(date.seconds).$d;
It will take
date: {
seconds: 1639506600,
nanoseconds: 0
}
and convert it to
Date Sat Nov 16 2019 00:00:00 GMT+0530 (India Standard Time)
To help those still looking around for an answer to convert Firestore Date to JS Date to display in the web app. Here goes an example using typescript...
import {
Timestamp,
} from "firebase/firestore";
interface IStuff {
createdAt: Timestamp;
}
const insertStuff = async (text: string) => {
await addDoc(collection(db, "coolstuff"), {
text,
createdAt: serverTimestamp(),
});
};
<p>{item.createdAt?.toDate().toDateString()}</p>
// OR
<p>{item.createdAt?.toDate().toLocaleTimeString()}</p>
Extending Waleed Tariq answer, to get a more readable string:
function formatDate(date) {
const formatDate = new Date(
date.seconds * 1000 + date.nanoseconds / 1000000
);
return formatDate.toLocaleTimeString('en-us', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}
const timeStamp = {nanoseconds: 184000000, seconds: 1664826910};
console.log(formatDate(timeStamp))
I had the same problem. And i figured out like this:
const createdAt = firebase.firestore.Timestamp.fromDate(new Date());
// then using dayjs library you can display your date as you want.
const formatDate = dayjs.unix(createdAt.seconds).format('YYYY-MM-DD');
Output should look like e.g. 2020-08-04
If you want don't want to lose the milliseconds you can do the following:
var myDate = a.record.dateCreated;
new Date((myDate.seconds + myDate.nanoseconds * 10 ** -9) * 1000);
i work in angular.
i have an interface and a field date: Date.
the angular pipe date no work: order.date | date:'medium'
i change type of field date in interface
date: firebase.firestore.Timestamp
the angular pipe date work, but with function toDate()
order.date.toDate() | date:'medium'
It's very simple really. Use this simple epoch converter function which converts epoch seconds into Javascript date and time.
function getUNIXTime(dt) {
let unix = new Date(dt * 1000);
return unix.toUTCString().slice(5, 16);
}
Pass the timestamp.seconds into this function then slice it according to your needs to get a string of text with date and time.
Normally using any type (i.e. loginDate:any) and toDate() worked without problem in my all projects. But in my last project it didn't. I saw seconds in Timestamp object is _seconds anymore (Firebase 8.6.8). This type of change may have affected it. I don't know but i had no time so i used an alternative solution. A custom pipe. It can be used as an alternative:
import { Pipe, PipeTransform } from '#angular/core';
import { formatDate } from '#angular/common';
#Pipe({
name: 'timestamp'
})
export class TimestampPipe implements PipeTransform {
transform(value: any, format?: string) {
if (!value) { return ''; }
if (!format) { format = 'dd MMM yy'; }
return formatDate(value._seconds * 1000, format, 'tr');
}
}
and
{{ item.endDate | timestamp}}
P.S. Type is not important with this pipe. Worked with loginDate:any or loginDate:Date well.
to store timestamp into firestore:
import * as firebaseAdmin from "firebase-admin";
const created = firebaseAdmin.firestore.FieldValue.serverTimestamp();
// type
created: FirebaseFirestore.Timestamp | FirebaseFirestore.FieldValue | undefined;
To read back as a js Date object
const createDate = (created as FirebaseFirestore.Timestamp).toDate();
To read back as RFC3339 string
const createDate = (created as FirebaseFirestore.Timestamp).toDate().toISOString();
Web Firestore Timestamp:
function dateToFirestoreTimestamp(dateString = ''){
var timestampDate = new Date(); // this will return current date-time
if(dateString != ''){
// this will return timestamp according to provided date-time
dateString = dateString.replace(' ', 'T');
timestampDate = new Date(dateString);
}
timestampDate = firebase.firestore.Timestamp.fromDate(timestampDate);
return timestampDate;
}
This is by far the most elegant, precise and easiest way to convert a firebase-timestamp to a date (no dependenceis etc. needed)
const date = new Intl.DateTimeFormat(
'de-De', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric'
}
).format(firebaseTimeStamp.toDate())
Here is a cheatsheet with all necesarry parameters
this is the different thing between firestore timestamp and Javascript Date() object. if you want to use javascript Date() object from firestore timestamp, this is what I do:
const foo = new Date(firestoreTimestamp.toDate());
then you can use the javascript Date() object, as usual. here are some references:
https://www.w3schools.com/jsref/jsref_obj_date.asp
For example, we want to retrieve the date from the Date() object with string format:
const foo = new Date(firestoreTimestamp.toDate());
foo.toLocaleDateString();
etc.
Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27
I have two variables in javascript like:
time: 02:00
date: 25-08-2017
and I'm wondering if I can put these into a Date() object and get the UTC date and time out of it in hours/minutes using getUTCDay(), getUTCHours() and getUTCMinutes() and place them back in the format I got them.
I can load moment.js for it but if I don't have to it would be nice if I can do it without.
Convert your strings to an ISO 8601 string and use it in the Date constructor. From there, you can get whatever data you need
let time = '02:00'
let date = '25-08-2017'
let iso8601Date = date.split('-').reverse().join('-')
let dt = new Date(`${iso8601Date}T${time}`) // will be interpreted as local time
const digitFormatter = new Intl.NumberFormat(undefined, {minimumIntegerDigits: 2})
console.info('Parsed date:', dt)
console.info('UTC date in dd-mm-yyyy:',
`${digitFormatter.format(dt.getUTCDate())}-${(digitFormatter.format(dt.getUTCMonth() + 1))}-${dt.getUTCFullYear()}`
)
console.info('UTC time:', `${digitFormatter.format(dt.getUTCHours())}:${digitFormatter.format(dt.getUTCMinutes())}`)
I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}
Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.
Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.
What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE
Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.
Probably and easy answer to this but I can't seem to find a way to get moment.js to return a UTC date time in milliseconds. Here is what I am doing:
var date = $("#txt-date").val(),
expires = moment.utc(date);
Any idea what I am doing wrong?
This is found in the documentation. With a library like moment, I urge you to read the entirety of the documentation. It's really important.
Assuming the input text is entered in terms of the users's local time:
var expires = moment(date).valueOf();
If the user is instructed actually enter a UTC date/time, then:
var expires = moment.utc(date).valueOf();
I use this method and it works. ValueOf does not work for me.
moment.utc(yourDate).format()
As of : moment.js version 2.24.0
let's say you have a local date input, this is the proper way to convert your dateTime or Time input to UTC :
var utcStart = new moment("09:00", "HH:mm").utc();
or in case you specify a date
var utcStart = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc();
As you can see the result output will be returned in UTC :
//You can call the format() that will return your UTC date in a string
utcStart.format();
//Result : 2019-06-24T13:00:00
But if you do this as below, it will not convert to UTC :
var myTime = new moment.utc("09:00", "HH:mm");
You're only setting your input to utc time, it's as if your mentioning that myTime is in UTC, ....the output will be 9:00
This will be the answer:
moment.utc(moment(localdate)).format()
localdate = '2020-01-01 12:00:00'
moment(localdate)
//Moment<2020-01-01T12:00:00+08:00>
moment.utc(moment(localdate)).format()
//2020-01-01T04:00:00Z
moment.utc(date).format(...);
is the way to go, since
moment().utc(date).format(...);
does behave weird...
This worked for me. Others might find it useful.
let date = '2020-08-31T00:00:00Z'
moment.utc(moment(date).utc()).format() // returns 2020-08-30T22:00:00Z
If all else fails, just reinitialize with an inverse of your local offset.
var timestamp = new Date();
var inverseOffset = moment(timestamp).utcOffset() * -1;
timestamp = moment().utcOffset( inverseOffset );
timestamp.toISOString(); // This should give you the accurate UTC equivalent.
This moment.utc(stringDate, format).toDate() worked for me.
This moment.utc(date).toDate() not.
here, I'm passing the date object and converting it into UTC time.
$.fn.convertTimeToUTC = function (convertTime) {
if($(this).isObject(convertTime)) {
return moment.tz(convertTime.format("Y-MM-DD HH:mm:ss"), moment.tz.guess()).utc().format("Y-MM-DD HH:mm:ss");
}
};
// Returns if a value is an object
$.fn.isObject = function(value) {
return value && typeof value === 'object';
};
//you can call it as below
$(this).convertTimeToUTC(date);
Read this documentation of moment.js here.
See below example and output where I convert GMT time to local time (my zone is IST) and then I convert local time to GMT.
// convert GMT to local time
console.log('Server time:' + data[i].locationServerTime)
let serv_utc = moment.utc(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment(serv_utc,"YYYY-MM-DD HH:mm:ss").tz(self.zone_name).format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to local time:' + data[i].locationServerTime)
// convert local time to GMT
console.log('local time:' + data[i].locationServerTime)
let serv_utc = moment(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment.utc(serv_utc,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to server time:' + data[i].locationServerTime)
Output is
Server time:2019-12-19 09:28:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to local time:2019-12-19 14:58:13
local time:2019-12-19 14:58:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to server time:2019-12-19 09:28:13
This worked for me:
const localtime = 1622516400000
moment(localtime).utc(true).format()
We can get 2 UTC date formats.
const date = '2021-07-20T18:30:00Z';
moment.utc(moment(date).utc()).format(); // 2021-07-19T18:30:00Z
moment.utc(moment(date).utc()).toISOString(); // 2021-07-20T18:30:00.000Z (Complete ISO-8601)
This works in my case.
Library: "moment": "^2.29.1",
moment().utc().format()
Don't you need something to compare and then retrieve the milliseconds?
For instance:
let enteredDate = $("#txt-date").val(); // get the date entered in the input
let expires = moment.utc(enteredDate); // convert it into UTC
With that you have the expiring date in UTC.
Now you can get the "right-now" date in UTC and compare:
var rightNowUTC = moment.utc(); // get this moment in UTC based on browser
let duration = moment.duration(rightNowUTC.diff(expires)); // get the diff
let remainingTimeInMls = duration.asMilliseconds();