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

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

Related

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>

Parse JSON DateTime object to local time in JQuery by ignoring timezone

I am facing an issue while parsing JSON Date Time object using moment(of course I tried many approaches suggested in Stackoverflow but nothing worked in my case).
In my application, I'm storing a DateTime value as UTC DateTime. Now when I'm displaying I need to display it according to the browser timezone. After going through many StackOverflow questions, I used "moment.js" as below
//From server, the Date object looks like /Date(1506510057813)/
//The equivalent DateTime value stored in Database is 2017-09-27 13:00:57.813
fuction DateTimeFormatter(value)
{
if (value != undefined) {
var newValue = new Date(moment.utc(value));
//But at this line, even with just moment(value) all I am getting is DateTime which is not same as UTC time.
//I don't want any time zone to get appended all I want is just 13:00:57
var newHours = newValue.getHours() - newValue.getTimezoneOffset() / 60;
var newMinutes = (newHours + '.0').split('.')[1] * 6;
newValue.setHours(newHours);
newValue.setMinutes(newMinutes);
return moment(newValue).format(applicationTableDateFormat);
}
else
return "";
}
Please let me know what I am doing wrong or is there any other way I can display time as per browser time zone.
Once you have a UTC moment, you can convert it to local.
moment.utc(value).local().format(...)
https://momentjs.com/docs/#/manipulating/local/
But it sounds like maybe your real problem is when you store the date. If you're storing it as UTC, make sure you actually convert the local value to UTC before you store it. That way when you read it, you get a predictable value that you can safely convert to any locale.
Angularjs has its own mechanism to display formatted dates on views you just needs an absolute representation of a date and it takes care of the rest. And by absolute, I mean, a Date which is settled in a timezone whether it's utc or not, you need to know what timezone you are talking about.
The date filter
It's a filter from the core module of angularjs and it accepts:
"... either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone." (Angularjs date filter)
The problem
Angularjs need a proper date input in order to display it correctly, in your case you seem to have the milliseconds format (sort of, /Date(1506510057813)/), you could use that and extract the numeric part and input that on the pipe, or you can change the server to send the ISO 8601 date (a.k.a., yyyy-MM-ddTHH:mm:ss.sssZ).
For example:
let rawDate = '/Date(1506510057813)/';
let re = /\/Date\((\d+)\)\//g; // regex to extract number from the string date
let myDate = new Date(Number(re.exec()[1])) // extract the milliseconds
Or
let rawDate = '2017-09-27T11:00:57.813Z';
let myDate = new Date(rawDate)// and you don't need to do anything else
Either way you'd end up with something like this:
<span> {{ myDate | date }}</span>

Convert EDT timestamp to local time in React Native/JavaScript

I get timestamp from server("2017-08-18T04:51:25EDT") which I want to convert to local time before displaying it to user. Can anyone show me how to achieve the same with moment.js or any other way ?
Use react-moment and remove the EDT from your string (I actually don't know this type of date format and moment says it's invalid, so remove it and it works).
Here's an example how to use it:
let dateToFormat = '2017-08-18T04:51:25';
return (
<Moment>{dateToFormat}</Moment>
)
Look at the docs of react-moment: https://www.npmjs.com/package/react-moment
EDT does not seem to be a valid time zone identifier, as you can see when pasting it into this fiddle:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_date_new_string
Can you get the date as a UTC timestamp or something else which is accepted by new Date("DateString") ?
Otherwise you would have to cut the EDT from the time stamp string, create a new Date object from it and then add the time difference manually.
Converting the date objcet to a locale time string can then be done with
dateObj.toLocaleDateString([locales [, options]])
as you can see here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Convert string to new Date object in UTC timeZONE

Can anyone let me know how to convert a string to a date Object with UTC time zone in ExtJs?
String is "2015-10-07T23:59:00". I would like to get the same in Date Object without changing the timezone.
First of all, your date string does not have a timezone.
When you make a JavaScript date object from a string, there are two possible outcomes you could expect:
You may want the date to be 23:59 Local (23:59 CEST in my case).
In this case, you want to use new Date("2015-10-07 23:59:00") with plain javascript (note the missing T), or Ext.Date.parse("2015-10-07T23:59:00","c");.
You may want the date to be 23:59 UTC (e.g. 01:59 CEST).
In this case, you want to use new Date("2015-10-07T23:59:00").
Of course, whenever you output the date, you have to get the date in the correct time zone as well. The console/toString will usually show it in local time. JavaScript does provide getUTC... methods if you require other time zones.
You see, using Time Zones with JavaScript is a painful experience. I would recommend to try moment.js if you need full time zone support.
You can use Ext.Date.parse.It gives Date Object as output.It syntax is:
Ext.Date.parse( String input, String format, [Boolean strict] )
For Example:
Ext.Date.parse("2015-10-07T23:59:00", "Y-m-dTH:i:s");
try
var millisFromEpoch = Date.parse('2015-10-07T23:59:00');
it will parse date in GMT timezone, Ext.date.parse use the current timezone instead

JavaScript date() Object returns NaN with getYear (and other)

I am currently having some issues converting a string dateTime object in JavaScript
I am assuming it is because my string cannot me used properly in a new Date() but I'm not sure that is the problem.
My Input: "2011-09-29 14:58:12"
My code:
var date = "2011-09-29 14:58:12";
var added = new Date(date);
var year = added.getYear();
However, my year var contains NaN. Same with getDay() or getMonth(). What is the problem?
ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved
You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard string format supported by the Date constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS, note the T rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers.
For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJS, MomentJS, date-fns, etc. to parse it for you.
The Date constructor will not parse a string for you. You'll need to use Date.parse to do that. Interestingly enough, Date.parse doesn't actually return a Date. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date constructor to get what you're looking for.
var d = new Date(Date.parse("2011-09-29 14:58:12"));

Categories