How to convert 12 hours datetime to timestamp with javascript - javascript

I have a datetime in following format 28/11/2015 09:41 PM and I want to convert it to epoch timestamp. How can I do that with javascript?
Additionally: I want to add and substracts 7200 seconds from that timestamp and convert it back to the original format. How can I do that? Is it necessary to convert datetime to timestamp first?

There is an awesome library available for that!
http://momentjs.com/

A great place to find information on JavaScript's built-in objects is the MDN, which has this article (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) on the datetime (or really just Date) object.
The way to get an epoch timestamp from a Date object is to use the getTime() function. It returns the number of milliseconds since 1 January, 1970.
var dateNow = Date.now();
var epochNow = dateNow.getTime();
You can then just add the seconds to it:
epochNow += (7200 * 1000); // * 1000 because it's in milliseconds
And then convert it back:
dateNow.setTime(epochNow);
Good luck!
NOTE
Beware inconsistencies in JavaScript Date implementations, especially in earlier versions of Internet Explorer. As some have noted, a good library like moment.js (http://momentjs.com/ ) is very helpful to prevent problems. However, if you are only using fully modern browsers or node, you shouldn't have as many problems.

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>

Convert epoch js with false time in device

My local sensor-device is confiugured with localtime:"11.01.1970
09:35:39","utctimestamp":894939.
I can not set a ntp-client in the device.
I receive timestamp values in ms unit.
How can i convert it to the actual time with Javascript ?
new Date(ms) gives 1970 year values
And how i convert timestamps like 2015-07-09 00:00:00 to ms epoch values ?
You can do this by using a javascript plugin called moment.js
They have a very nicely maintained documentation.
Basically you can get the current time in javascript like:
new Date().getTime();
And this value can be converted to different formats using moment.js as per their documentation.

JS Dates only with UTC timezone

Is there some way to tell Javascript that it should never use anything but the UTC timezone?
When I create a new Date object, it gets my browsers timezone, but this will muck up when transporting via JSON.
All dates and times in the app are naive and has no use for the users timezone. So creating and working with only UTC times would be just fine, but no matter what I do, I just get what my date would look like in UTC and thats just not good enough.
I am using Bakcbone and DateJS if that makes any difference.
Any ideas on this?
Instead of transporting the string representation of the date, new Date().milliseconds. This is the UNIX time, i.e.
Integer value representing the number of milliseconds since 1 January
1970 00:00:00 UTC.
and therefore independent of the timezone.
Alternatively, construct the date string yourself, but use the getUTC* methods:
var d = new Date();
alert("It's " + d.getUTCHours() + ':' + d.getUTCSeconds());
I ended up just using .toString() and sending that along with the JSON post. Seemed like the simplest thing to do.

Daylight savings time and JavaScript timezone conversions

I have this dilemma with JavaScript. I need to convert a list of dates from client's local timezone to NYC (EST) timezone. I'm using the function below:
Date.prototype.toNycTime = function() {
var localTime = this.getTime();
var localOffset = this.getTimezoneOffset() * 60000;
var utc = localTime + localOffset;
this.setTime(utc - 3600000 * 5);
return this;
};
It works OK. One problem is that I need to adjust UTC offset every time there's a daylight saving switch in USA. And that works OK for any date that is before the next switch (earliest coming is 13-MAR-2011). But it doesn't work on dates after the switch. I don't know of any build-in JS function in any of the browsers that will do the conversion for me.
Is there a good library out there that will allow me to do some universal conversions? Or can anyone offer any tips on the code above? I'm trying to avoid programming in the dates/times for the conversion and having to look up all the time.
I'm dealing with this exact problem... corporate users throughout the world, but 'corporate time' is PST/PDT which includes daylight saving time.
How I've been approaching it:
I actually parse a POSIX timezone string for PacificTime starting with
PST8PDT,M3.2.0/2,M11.1.0/2
and reformat those into parseable date strings for when clocks more forward and back.
Using the hours-offset embedded in the TZ string, I convert the forward and back times to epoch timestamps and use an if-then to calculate if corporate time is currently DST.
This yields an offset from UTC I can use to convert local 'epoch' times (which are already in UTC) to a conceptual localtime (that is actually converted in UTC time, but looks local).
I have to do this as 'flot' does everything in UTC
http://www.datejs.com/
Datejs is an open-source JavaScript Date Library.
Comprehensive, yet simple, stealthy and fast. Datejs has passed all trials and is ready to strike. Datejs doesn’t just parse strings, it slices them cleanly in two.

Categories