How to get julian Date from Date Control using Javascript [duplicate] - javascript

I have requirement to calculate jday in javascript , for doing client side validation , Can any one help me how to calculate JDAY in javascript or script to change given JDAY to actual date or vice versa .
To know what is JDay ,I found the following site ,
http://www.pauahtun.org/Software/jday.1.html
Am also refering the below site for calculation which is mentioned in JAVA
http://www.rgagnon.com/javadetails/java-0506.html
Thank you in advance

Julian Day
The Julian Day is the number of elapsed days since the beginning of a cycle of 7980 years.
Invented in 1583 by Joseph Scaliger, the purpose of the system is to make it easy to compute an integer (whole number) difference between one calendar date and another calendar date.
The 7980 year cycle was derived by combining several traditional time cycles (solar, lunar, and a particular Roman tax cycle) for which 7980 was a common multiple.
The starting point for the first Julian cycle began on January 1, 4713 B.C. at noon GMT, and will end on January 22, 3268 at noon GMT, exactly 7980 whole days later.
As an example, the Julian day number for January 1, 2016 was 2,457,389, which is the number of days since January 1, 4713 B.C. at that day.
How to calculate it
As we know that Unix time is the number of seconds since 00:00:00 UTC, January 1, 1970, not counting leap seconds, and also called Epoch, we can use some math to calculate the Julian Day when we already have the Unix time.
GMT and UTC share the same current time in practice, so for this, there should be no difference.
To start with, we need to know the number of days from when the Julian cycle began, until Unix timestamps began.
In other words, the number of days from January 1, 4713 B.C. at 12:00:00 GMT, until January 1, 1970 at 00:00:00 UTC.
Having this set number of days, that never change, we can just add the number of days from January 1, 1970 until today, which is what Javascript returns anyway, to get the Julian Day.
Without adding up all those years, but simply by searching the web, it tells us that the difference in days between the year 4713 B.C. and 1970 A.D. is 2440588 days, and because the Julian Cycle began at noon, not at midnight, we have to subtract exactly half a day, making it 2440587.5 days.
So what we have now is 2440587.5 days + UNIX TIME in days === Julian Day
With some simple math we can figure out that a day is 86,400 seconds long, and the Unix timestamp is in milliseconds when using Javascript, so UNIX TIME / 86400000 would get us the number of days since Thursday, 1 January 1970, until today.
Now for just the day, we wanted the whole number of days, and not the fractional, and can just round it down to the closes whole day, doing something like
Math.floor((UNIX TIME / 86400000) + 2440587.5);
Julian Date
Sometimes in programming, a "Julian Date" has come to mean the number of days since the year started, for instance June 1, 2016 would be 152 days into that year etc.
The correct use of "Julian Date" is a Julian Day with a timestamp added as a fractional part of the day.
Taking the example at the top of this answer, where January 1, 2016 was the Julian Day 2,457,389 , we can add a time to that.
The Julian Day starts at noon, with no fractional time added, and so at midnight it would be 2457389.5 and at 18:00, or six hours after noon, it would be 2457389.25, adding "half a day", "quarter of a day" etc.
Calculating it, again
This means 0.1 Julian Date is the same as 24 hours divided by 10, or 24 / 10 === 2.4 hours, or in other words, Julian Day timestamps are fractional with decimals (one tenth of a day etc).
Lets look at some Javascript functions, firstly the Date constructor.
Javascript only has access to the local time on the computer it runs on, so when we do new Date() it does not neccessarely create an UTC date, even if UNIX time is in UTC, new Date gives you the number of seconds from epoch until whatever local time your computer has, and does not take your timezone into consideration.
Javascript does however have Date.UTC, which would return the date in UTC format, lets check the difference, and this will of course differ according to the timezone you've set the local system to.
var regular_date = new Date(2016, 1, 1, 0, 0, 0);
var UTC_date = Date.UTC(2016, 1, 1, 0, 0, 0);
var difference = UTC_date - regular_date;
document.body.innerHTML = 'The difference between your local time and UTC is ' +(difference/1000)+ ' seconds';
Remember the part at the begin of this chapter, about 0.1 Julian Date being the same as 24 hours divided by 10, or 24 / 10 === 2.4 hours, well, 2.4 hours is 144 minutes, and now lets look quickly at Javascripts getTimezoneOffset() method, the docs say
The getTimezoneOffset() method returns the time-zone offset from UTC,
in minutes, for the current locale.
So, it returns the offset for the systems timezone in minutes, that's interesting as most javascript methods that deal with dates returns milliseconds.
We know that a 1/10 of a day is 144 minutes, so 10/10, or a whole day, would be 1440 minutes, so we could use some math to counteract the local systems timezone, given in minutes, and divide it by the number of minutes in a day, to get the correct fractional value
So now we have
2440587.5 days + UNIX TIME in days === Julian Day
and we know Javascripts Date constructor doesn't really use UTC for the current date, but the system time, so we have to have
TIMEZONEOFFSET / 1440
joining them together we would get
(JAVASCRIPT TIME / 86400000) - (TIMEZONEOFFSET / 1440) + 2440587.5
// ^^ days since epoch ^^ ^^ subtract offset ^^ ^^days from 4713 B.C. to 1970 A.D.
Translating that to javascript would be
var date = new Date(); // a new date
var time = date.getTime(); // the timestamp, not neccessarely using UTC as current time
var julian_day = (time / 86400000) - (date.getTimezoneOffset()/1440) + 2440587.5);
Now this is what we should use to get the Julian Day as well, taking measures to remove the timezone offset, and of course without the fractional time part of the Julian Date.
We would do this by simpy rounding it down to the closest whole integer
var julian_date = Math.floor((time / 86400000) - (date.getTimezoneOffset()/1440) + 2440587.5));
And it's time for my original answer to this question, before I made this extremely long edit to explain why this is the correct approach, after complaints in the comment field.
Date.prototype.getJulian = function() {
return Math.floor((this / 86400000) - (this.getTimezoneOffset() / 1440) + 2440587.5);
}
var today = new Date(); //set any date
var julian = today.getJulian(); //get Julian counterpart
console.log(julian)
.as-console-wrapper {top:0}
And the same with the fracional part
Date.prototype.getJulian = function() {
return (this / 86400000) - (this.getTimezoneOffset() / 1440) + 2440587.5;
}
var today = new Date(); //set any date
var julian = today.getJulian(); //get Julian counterpart
console.log(julian)
.as-console-wrapper { top: 0 }
And to finish of, an example showing why
new Date().getTime()/86400000 + 2440587.5
doesn't work, at least not if your system time is set to a timezone with an offset, i.e. anything other than GMT
// the correct approach
Date.prototype.getJulian = function() {
return (this / 86400000) - (this.getTimezoneOffset() / 1440) + 2440587.5;
}
// the simple approach, that does not take the timezone into consideration
Date.prototype.notReallyJulian = function() {
return this.getTime()/86400000 + 2440587.5;
}
// --------------
// remember how 18:00 should return a fractional 0.25 etc
var date = new Date(2016, 0, 1, 18, 0, 0, 0);
// ^ ^ ^ ^ ^ ^ ^
// year month date hour min sec milli
var julian = date.getJulian(); //get Julian date
var maybe = date.notReallyJulian(); // not so much
console.log(julian); // always returns 2457389.25
console.log(maybe); // returns different fractions, depending on timezone offset
.as-console-wrapper { top: 0 }

new Date().getTime()/86400000 + 2440587.5
will get the unix time stamp, convert it to days and add the JD of 1970-01-01, which is the epoch of the unix time stamp.
This is what astronomers call julian date. It is well defined. Since neither Unix time stamp nor JD take leap seconds into account that does not reduce the accuracy. Note that JD need not be in timezone UTC (but usually is). This answer gives you the JD in timezone UTC.

According to wikipedia:
a = (14 - month) / 12
y = year + 4800 - a
m = month + 12a - 3
JDN = day + (153m + 2) / 5 + 365y + y/4 - y/100 + y/400 - 32045
If you're having a more specific problem with the implementation, provide those details in the question so we can help further.
NOTE : This is not correct because the "floor brackets" on Wiki were forgotten here.
The correct formulas are:
a = Int((14 - Month) / 12)
y = Year + 4800 - a
m = Month + 12 * a - 3
JDN = Day + Int((153 * m + 2) / 5) + 365 * y + Int(y / 4) - Int(y / 100) + Int(y / 400) - 32045

JD =>
const millisecondsSince1970Now = new Date+0
const julianDayNow = 2440587.5+new Date/864e5
const dateNow = new Date((julianDayNow-2440587.5)*864e5)
There seems to be confusion about what a Julian-Day is, and how to calculate one.
Javascript time is measured as GMT/UTC milliseconds UInt64 from Jan 1, 1970 at midnight.
The Month, Day, Year aspects of the JavaScript Date function are all implemented using Gregorian Calendar rules. But Julian "Days" are unaffected by that; however mapping a "day-count" to a Julian Month, Day, Year would be.
Calculating Julian-Day conversions are therefore a relative day count from that point in time (Jan 1, 1970 GMT/UTC Gregorian).
The Julian-Day for Jan 1, 1970 is 2440587.5 (0.5 because JulianDays started at NOON).
The 864e5 constant is JavaScript notation for 86,400,000 (milliseconds/day).
The only complexities are in calculating Julian dates (days) prior to adoption of the 1582 Gregorian calendar whose changes mandated from Pope Gregory were to correct for Leap Year drift inaccuracies affecting Easter. It took until around 1752 to be fully adopted throughout most countries in the world which were using the Julian Calendar system or a derivative (Russia and China took until the 20th century).
And the more egregious errors in the first 60 years of Julian date implementation from Julius Caesar's 46BC "reform" mandate where priests made mistakes and people misunderstood as they folded a 14/15 month calendar. (hence errors in many religious dates and times of that period).
🎪 None of which applies in JavaScript computation of Julian Day values.
See also: (from AfEE EdgeS/EdgeShell scripting core notes)
Astronomy Answers - Julian Day Number (multi-calendrical conversions)
Julian calendar
Atomic Clocks
JavaScript operator precedence
Microsoft FILETIME relative to 1/1/1601 epoch units: 10^-7 (100ns)
UUID/GUIDs timestamp formats - useful for time-date conversion also
"Leap Second" details
There is a separate subtlety "leap-second" which applies to astronomical calculations and the use of atomic clocks that has to do with earth orbital path and rotational drift.
i.e., 86,400.000 seconds per day needs "adjustment" to keep calendars (TimeZones, GPS satellites) in sync as it is currently 86,400.002.

It seems that the final code given in the accepted answer is wrong. Check the "official" online calculator at US Naval Observarory website:
http://aa.usno.navy.mil/data/docs/JulianDate.php
If someone knows the correct answer to a answer time and calendar, it's USNO.

Additionally, there is an npm package for this:
julian
Convert between Date object and Julian dates used in astronomy and history
var julian = require('julian');
var now = new Date(); // Let's say it's Thu, 21 Nov 2013 10:47:02 GMT
var jd = '';
console.log(jd = julian(now)); // -> '2456617.949335'
console.log(julian.toDate(jd)); // -> Timestamp above in local TZ
https://www.npmjs.com/package/julian

Whatever you do, DON'T USE getTimezoneOffset() on dates before a change of policy in the current Locale, it's completely broken in the past (it doesn't apply iana database rules).
For example, if I enter (UTC date 1st of october 1995 at 00:00:00):
var d=new Date(Date.UTC(1995, 9, 1, 0, 0, 0)); console.log(d.toLocaleString()); console.log(d.getTimezoneOffset());
in the javascript console in Chrome, it prints (I'm in France):
01/10/1995 at 01:00:00 <= this is winter time, +1:00 from UTC
-120 <= BUT this is summer time offset (should be -60 for winter)
Between 1973 and 1995 (included), DST (-120) terminated last Sunday of September, hence for 1st of October 1995, getTimezoneOffset() should return -60, not -120. Note that the formatted date is right (01:00:00 is the expected -60).
Same result in Firefox, but in IE and Edge, it's worse, even the formatted date is wrong (01‎/‎10‎/‎1995‎ ‎02‎:‎00‎:‎00, matching the bad -120 result of getTimezoneOffset()). Whatever the browser (of these 4), getTimezoneOffset() uses the current rules rather than those of the considered date.
Variation on the same problem when DST didn't applied in France (1946-1975), Chrome console:
d=new Date(Date.UTC(1970, 6, 1, 0, 0, 0)); console.log(d.toLocaleString()); console.log(d.getTimezoneOffset());
displayed:
‎01‎/‎07‎/‎1970‎ ‎01:‎00‎:‎00 <= ok, no DST in june 1970, +1:00
-120 <= same problem, should be -60 here too
And also, same thing in Firefox, worse in IE/Edge (01‎/‎07‎/‎1970‎ ‎02:‎00‎:‎00).

I did this for equinox and solistice. You can use the function for any Julian date.
It returns the Julian date in the calender date format: day/month.
Include year and you can format it anyway you want.
It's all there, year, month, day.
Since Equinox and Solistice are time stamps rather than dates, my dates in the code comes back as decimals, hence "day = k.toFixed(0);". For any other Julian date it should be day = k;
// For the HTML-page
<script src="../js/meuusjs.1.0.3.min.js"></script>
<script src="../js/Astro.Solistice.js"></script>
// Javascript, Julian Date to Calender Date
function jdat (jdag) {
var jd, year, month, day, l, n, i, j, k;
jd = jdag;
l = jd + 68569;
n = Math.floor(Math.floor(4 * l) / 146097);
l = l - Math.floor((146097 * n + 3) / 4);
i = Math.floor(4000 * (l + 1) / 1461001);
l = l - Math.floor(1461 * i / 4) + 31;
j = Math.floor(80 * l / 2447);
k = l - Math.floor(2447 * j / 80);
l = Math.floor(j / 11);
j = j + 2 - 12 * l;
i = 100 * (n - 49) + i + l;
year = i;
month = j;
day = k.toFixed(0); // Integer
dat = day.toString() + "/" + month.toString(); // Format anyway you want.
return dat;
}
// Below is only for Equinox and Solistice. Just skip if not relevant.
// Vernal Equinox
var jv = A.Solistice.march(year); // (year) predefined, today.getFullYear()
var vdag = jdat(jv);
// Summer Solistice
var js = A.Solistice.june(year);
var ssol = jdat(js);
//Autumnal Equinox
var jh = A.Solistice.september(year);
var hdag = jdat(jh);
// Winter Solistice
var jw = A.Solistice.december(year);
var vsol = jdat(jw);

Related

Convert getFullYear() in seconds in Javascript

Are there any way to convert the GetFullYear() in real time seconds from the beginning of the current year? Instead of having a output of 2017, i have a dynamic seconds until the end of the year.
As well as obtaining the maximum value of the GetFullYear() converted in seconds to make some calculations.
Thanks in advance
var date1 = new Date("1/1/2017");
var date2 = new Date("2/2/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));//returns 32
var time_in_seconds = diffDays*60*60;// calculate the date in seconds.
Are there any way to convert the GetFullYear() in real time seconds from the beginning of the current year?
To get the difference in milliseconds between two dates, just subtract them. To get ms from the start of the year, subtract now from a date for 1 Jan at 00:00:00, e.g.
function msSinceStartOfYear() {
var now = new Date()
return now - new Date(now.getFullYear(), 0);
}
console.log(msSinceStartOfYear());
As well as obtaining the maximum value of the GetFullYear() converted in seconds to make some calculations.
According to ECMA-262, the maximum time value is 9,007,199,254,740,992, which is approximately 285,616 years after the epoch of 1 Jan 1970, or the year 287,586. So that is the theoretical maximum value of getFullYear.
However:
new Date(9007199254740992)
returns null. The actual range is exactly 100,000,000 days, so to get the maximum value, multiply days by the number of milliseconds per day:
new Date(100000000 * 8.64e7).getUTCFullYear() // 275,760
converted to seconds:
new Date(Date.UTC(275760, 0)) / 1000 // 8,639,977,881,600 seconds
but I have no idea why you want to do that. I've used UTC to remove timezone differences. Using "local" timezone changes the values by the timezone offset.

How to add 24hr in current unix timestamp in NodeJs or in javascript?

I would like to add 24 hours to the unix timestamp for now in nodejs or in javascript. I also would like to know is there is any direct function or property in Date DOM object.
I found the relevent function in PHP. This code will returns new unix time after adding 24hrs in current unix timestamp.
$currentUnixTime=time();
$newUnixTime=strtotime('+1 day', $currentUnixTime);
return newUnixTime;
var myDate = new Date();
myDate.setHours(myDate.getHours()+24);
return myDate;
If you specifically want to add one day, you should use momentjs library, which is available both for frontent and nodejs.
var now = new Date()
var tomorrow = moment(now).add(1, 'day');
This is more robust than adding 24 hours because it takes into account DST changes. For that sole reason you should avoid direct Date manipulation in JS in most of the cases.
http://momentjs.com/docs/#/manipulating/add/
Special considerations for months and years
If the day of the month on the original date is greater than the
number of days in the final month, the day of the month will change to
the last day in the final month.
moment([2010, 0, 31]); // January 31
moment([2010, 0, 31]).add(1, 'months'); // February 28
There are also special considerations to keep in mind when adding time
that crosses over daylight saving time. If you are adding years,
months, weeks, or days, the original hour will always match the added
hour.
var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US m.hours(); // 5
m.add(1, 'days').hours(); // 5
If you are adding hours, minutes, seconds, or milliseconds, the
assumption is that you want precision to the hour, and will result in
a different hour.
var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US m.hours(); // 5
m.add(24, 'hours').hours(); // 6

date object returns random date for invalid months/day

This code:
var dt = new Date('82/66/2005');
...gives a value for dt as Wed Nov 25 1992 00:00:00 GMT+0530 (IST) on Firefox.
How?
Fiddle - http://jsfiddle.net/4jyT3/1/
That date is not in a format that is specified to be supported by the Date constructor. I'm not surprised to find that most engines call it invalid, but apparently Firefox is attempting to make a date out of that. Even though it's not specified, most engines support month/day/year and all, last I checked, support year/month/day. Firefox appears to be applying year/month/day to the input, where most browsers see the invalid values and go with "invalid."
So Firefox is seeing 82 for year (and assuming 1982), 66 for month, and 2005 for day. JavaScript is usually very forgiving about out-of-bound values on dates, moving to the next month and such as necessary. And that's what's happening here: If you take January 1st 1982 and add a further 65 months and 2004 days, you end up on Nov 25 1992.
This code will reliably give you the date you mentioned:
var dt = new Date(1982, 65, 2005);
(65 instead of 66 because in the number form, months start with 0, but in string form, they start with 1.)
I can't re-produce this in Chrome, but I'll explain how FireFox arrives here.
new Date('82-66-2005');
Invalid date, let's guess what you wanted based on what we know about dates.
hyphen - format is usually yyyy-mm-dd
yy is short for 19yy
there are 12 months, so month 13 is Januaray of next year
similarly for days
So using this knowledge lets estimate it, assuming 365.25 days per year and 30.5 days per month.
// input
var year = 1982, // 19yy
bigMonth = 66,
bigDay = 2005;
// adjust day for years
var day = bigDay % 365.25;
year = year + (bigDay - day) / 365.25;
// adjust day for months
bigDay = day;
day = bigDay % 30.5;
bigMonth = bigMonth + (bigDay - day) / 30.5;
// adjust month for years
var month = bigMonth % 12;
year = year + (bigMonth - month) / 12;
console.log(year, month, day); // 1992 11 26.25
So it would be about the Nov 26th, 1992, which is pretty close to how your browser calculated it (it didn't need to estimate).

JavaScript: Convert Day/Week Into Year

I have been using Stack Overflow for a number of months now, but this is my first post.
I require a function to convert a week number and and day of week into a dd/mm/yyyy format.
The date values i have to work with are in the format day/weekNumber. So for example: 3/43 converts to Wednesday 24 October 20XX. The year value will be the current year.
The day value starts at 1 (Monday).
I have found lots of functions on the internet (such as this, this and this). Some work with ISO 8601 dates, which i do not think will work for me. And i have not yet found one that works for me.
Thanks in advance,
This solution does require an extra library to be added, but I think it is really worth it. It is a momentjs library for manipulating dates and time. It is actively maintained and has a great documentation. Once you get the values for day and weekNumber (in our case 3 and 43), you should do as follows:
function formatInput(day, weekNumber){
var currentDate = moment(new Date()); // initialize moment to a current date
currentDate.startOf('year'); // set to Jan 1 12:00:00.000 pm this year
currentDate.add('w',weekNumber - 1); // add number of weeks to the beginning of the year (-1 because we are now at the 1st week)
currentDate.day(day); // set the day to the specified day, Monday being 1, Sunday 7
alert(currentDate.format("dddd, MMMM Do YYYY")); // return the formatted date string
return currentDate.format("dddd, MMMM Do YYYY");
}
I think this library might be useful to you later on and there are plenty of possibilities regarding date and time manipulation, as well as formatting options. There is also a great documentation written for momentjs.
So assuming you have the values of 3 and 43 separately, you can just do some simple maths on the first day of the current year:
Get 1st January Current Year
Add (43 * 7 + 3)
Something like this maybe:
var currentDate = new Date();
var startOfYear = new Date(currentDate.getFullYear(), 0, 1);//note: months start at 0
var daysToAdd = (43 * 7) + 3;
//add days
startOfYear.setDate(startOfYear.getDate() + daysToAdd);
Here is an example
EDIT
On second thoughts, I think I was wrong with your requirements. It seems you require a specific day of the week. Check this out for a better solution.
The problem is that it all depends on your definition of a week. This year starts on a sunday, so does that mean that 02/01/2012 (the first monday of this year) is the start of the second week?
My latest example will first find the start of the specified week, and then find the next occurrence of the specified day
According to ISO when dealing with week dates, the week starts on Monday and the first week of the year is the one that contains the first Thursday of the year. So for 2012, the first week started on Monday, 2 January and the first week of 2013 will start on Monday, 31 December 2012.
So if 3/43 is the third day of the 43rd week (which is the ISO date 2012-W43-3), then it can be converted it to a date object using:
function customWeekDateToDate(s) {
var d, n;
var bits = s.split('/');
// Calculate Monday of first week of year this year
d = new Date();
d = new Date(d.getFullYear(),0,1); // 1 jan this year
n = d.getDay();
d.setDate(d.getDate() + (-1 * n +( n<5? 1 : 8)));
// Add days
d.setDate(d.getDate() + --bits[0] + --bits[1] * 7);
return d;
}
console.log(customWeekDateToDate('3/43')); // 01 2012-10-24
Note that this uses dates, otherwise daylight saving changeovers may result in the wrong date.

Getting current date in milliseconds (UTC) (NO use of strings)

Well, you might think that this question has already been asked, but I think it has not. The solutions I've read about all had this "jigsaw puzzle" technique (like getUTCMonth() + getUTCMinutes + ...).
But as I only want to compare the elapsed seconds between two UTC (!) dates, this does not apply.
As everybody knows, you can get the current (non-UTC) date by:
var d = new Date();
var t_millis = d.getTime();
But this is NOT what I want. I'd like to have the current system date in UTC and in milliseconds, so not mess about with strings at all. AFAIK the variable t_millis will contain the millisecond value of the current timestamp in GMT, not UTC.
(Since d is in GMT as well. Unless getTime() does a sort of implicit time zone conversion, i. e. adding the offset BEFORE giving out the milliseconds, but I've never read about that anywhere)
So is there really no other way than adding the offset to the time value?
I'm desperately missing a function like getUTCTimeMillis() known from other languages.
This is an old question but for the sake of the new visitors here is THE CORRECT ANSWER:
Date.now();
It returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
The millisecond value of the time-of-day is going to be the same regardless of your time zone. That is, there are no time zones on planet Earth that differ from one another by a number of milliseconds greater than zero. (They may differ by an integer number of hours or even minutes, but not seconds or milliseconds.)
That said, the value you get back from getTime() is a UTC-relative timestamp. If two web browsers at widely different spots on the globe create a Date object at the same time, they'll both get the same value from .getTime() (assuming the clocks are synchronized, which is of course highly unlikely).
Here: 1338585185539 That's a timestamp I just got from my browser. I'm in Austin, TX, and now it's 4:13 in the afternoon (so that timestamp will be from slightly before that). Plug it into a Date instance on your machine and see what it says.
(edit — for posterity's sake, that timestamp is from 1 June 2012.)
how about:
var now = new Date();
var utc_now = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
console.log('UTC: ' + utc_now) // correct UTC time but wrong timezone!
console.log('UTC (in ms): ' + utc_now.getTime())
I have used this function to solve the problem.
function getUTCNow()
{
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
The getTime function returns the number of milliseconds elapsed since
1 January 1970 00:00:00 in the client timezone.
getTimezoneOffset return offset in minutes between Client timezone and UTC.
offset = offset * 60000; this operation transform minutes in miliseconds.
subtracting the offset get the number of milliseconds elapsed since 1
January 1970 00:00:00 UTC.
To get the timestamp from a date in UTC, you need to take in consideration the timezone and daylight savings for that date. For example, a date in January or in July could mean 1 hour difference.
The option below does just that.
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
It can be used as in:
var date = new Date();
var timestamp = date.getUTCTime();

Categories

Resources