Converting unix timestamp to a .NET Date Time in javascript - javascript

I'm interfacing with an api and they use .NET so all of my time stamps need to conform to .NET's Date Time format which looks something like this
/Date(1379142000000-0700)/
I would like to convert unix times to this format using javascript. I've seen this function for moment.js but this dosn't return the unix/epoch formatting and it's in the wrong direction.
How can I convert unix timestamp to .net time formatting with javascript?
solutions using moment.js are good, and bonus points for converting from .net to unix as well.

If you have a date object, it seems like you need the UTC millisecond time value and the timezone offset in hours and minutes (hhmm). So presuming that the UNIX time value is UTC and that the ".NET" time string is a local time value with offset, then:
function unixTimeToDotNetString(v) {
// Simple fn to add leading zero to single digit numbers
function z(n) {
return (n < 10 ? '0' : '') + n;
}
// Use UNIX UTC value to create a date object with local offset
var d = new Date(v * 1e3);
// Get the local offset (mins to add to local time to get UTC)
var offset = d.getTimezoneOffset();
// Calculate local time value by adding offset
var timeValue = +d + offset * 6e4;
// Get offset sign - reverse sense
var sign = offset < 0 ? '+' : '-';
// Build offset string as hhmm
offset = Math.abs(offset);
var hhmm = sign + z(offset / 60 | 0);
hhmm += z(offset % 60);
// Combine with time value
return timeValue + hhmm;
}
var unixTime = 1393552984;
console.log(unixTime + ' : ' + unixTimeToDotNetString(unixTime)); // 1393552984 : 1393517104000+1000
The difference between the two time values shoudl be equivalent to the offset in milliseconds (in this case where the timezone is UTC+1000 it's 36000000).

Related

How to convert ISO string format date time to next hour

I am using the following function to convert my date in RFC3339. I want it to convert in upper limit.
Can anyone assist me, how do I convert it to upper limit?
const date = new Date();
// RFC 3339 format
const targetTime = date.toISOString();
Current output is:
2022-12-20T05:26:12.968Z
Expected output should be
2022-12-20T06:00:00Z
See this answer, very similar but you can replace Math.round with Math.ceil to round up like you want and in addition you'll need to get the percentage the hour is complete (assuming you don't want to round up exact hours).
const milliSecondsInHour = 60*60*1000;
const roundDateToNextHour = (date: Date) => {
const percentHourComplete = (x.getTime() % milliSecondsInHour) / milliSecondsInHour;
date.setHours(date.getHours() + Math.ceil(percentHourComplete));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}
If the intention is to the next full UTC hour, test if UTC minutes, seconds or milliseconds are greater than zero. If any of them are, increment the hour and zero the other values, e.g.:
// If the provided date is not exactly on the UTC hour,
// return a date that is the next full UTC hour after
// the provided date.
function toFullUTCHour(date) {
let d = new Date(+date);
d.setUTCHours(d.getUTCHours() + (d.getUTCMinutes() || d.getUTCSeconds() || d.getUTCMilliseconds? 1 : 0), 0,0,0);
return d;
}
let d = new Date()
console.log(d.toISOString() + '\n' +
toFullUTCHour(d).toISOString());
// Simplified version, only works in general for UTC hour
function ceilUTCHour(date = new Date()) {
let d = new Date(+date);
d.setHours(d.getHours() + (d%3.6e6? 1 : 0), 0, 0, 0);
return d;
}
console.log(ceilUTCHour(d).toISOString());
Since, in ECMAScript, UTC days are always exactly 8.64e7 ms long and hours are always exactly 3.6e6 ms long, you can just get the remainder of the current UTC time value and if it's not zero (which will be almost always) add 1 to the UTC hour, then zero the minutes seconds and milliseconds as for the ceilUTCHour function above.

Fetch UTC Date offset based on date format

I have date with format '2021-05-01T23:59:59.999-05:00'
Need to fetch utc offset value like 300, 330 etc.
Can someone help here.Any Answer without using moment.js is appreciated.
So extracting value -05:00 from '2021-05-01T23:59:59.999-05:00'
The function Date.getTimezoneOffset() will only ever give you the offset between the client machine timezone and UTC, it won't give you the UTC offset as specified in the ISO date string.
Given that the dates are in ISO-8601 format, we can parse the UTC offset from the data, it will be in the format ±[hh]:[mm], ±[hh][mm], ±[hh] or 'Z' for UTC / Zulu time.
Negative UTC offsets describe a time zone west of UTC±00:00, where the civil time is behind (or earlier) than UTC so the zone designator will look like "−03:00","−0300", or "−03".
Positive UTC offsets describe a time zone at or east of UTC±00:00, where the civil time is the same as or ahead (or later) than UTC so the zone designator will look like "+02:00","+0200", or "+02".
We'll use regular expressions to parse the timezone offsets, this will work on IE 11 too.
function getUTCOffsetMinutes(isoDate) {
// The pattern will be ±[hh]:[mm], ±[hh][mm], or ±[hh], or 'Z'
const offsetPattern = /([+-]\d{2}|Z):?(\d{2})?\s*$/;
if (!offsetPattern.test(isoDate)) {
throw new Error("Cannot parse UTC offset.")
}
const result = offsetPattern.exec(isoDate);
return (+result[1] || 0) * 60 + (+result[2] || 0);
}
const inputs = [
'2021-05-01T23:59:59.999+12:00',
'2021-05-01T23:59:59.999+10',
'2021-05-01T23:59:59.999+0530',
'2021-05-01T23:59:59.999+0300',
'2021-05-01T23:59:59.999Z',
'2021-05-01T23:59:59.999-05:00',
'2021-05-01T23:59:59.999-07:00',
];
for(var i = 0; i < inputs.length; i++) {
console.log('input:', inputs[i], 'offsetMinutes:', getUTCOffsetMinutes(inputs[i]));
}
Pretty much the same as #TerryLennox but deals with:
Seconds in the offset—fairly common before 1900, added as decimal part of minutes
Missing offset—local, returns undefined
function parseOffset(ts) {
let [all,hr,min,sec] = (''+ts).match(/([+-]\d{2}|Z):?(\d{2})?:?(\d{2})?$/) || [];
let sign = hr < 0 ? -1 : 1;
return !all ? all : // No match, return undefined
hr == 'Z' ? 0 :
hr * 60 + (min? sign * min : 0) + (sec? sign * sec / 60 : 0);
}
['2021-05-01T23:59:59.999-05:30',
'2021-05-01T23:59:59.999+05:30',
'2021-05-01T23:59:59.999-0530',
'2021-05-01T23:59:59.999+0530',
'2021-05-01T23:59:59.999-05',
'2021-05-01T23:59:59.999+05',
'2021-05-01T23:59:59.999+053012',
'2021-05-01T23:59:59.999+05:30:12',
'2021-05-01T23:59:59.999Z',
'2021-05-01T23:59:59.999',
'blah'
].forEach(ts => console.log(ts + ' -> ' + parseOffset(ts)));

How to get the timezone offset in GMT(Like GMT+5:30) in javascript [duplicate]

In C# you can use
System.TimeZone.CurrentTimeZone.GetUtcOffset(someDate).Hours
But how can I get UTC offset in hours for a certain date (Date object) in javascript?
Vadim's answer might get you some decimal points after the division by 60; not all offsets are perfect multiples of 60 minutes. Here's what I'm using to format values for ISO 8601 strings:
function pad(value) {
return value < 10 ? '0' + value : value;
}
function createOffset(date) {
var sign = (date.getTimezoneOffset() > 0) ? "-" : "+";
var offset = Math.abs(date.getTimezoneOffset());
var hours = pad(Math.floor(offset / 60));
var minutes = pad(offset % 60);
return sign + hours + ":" + minutes;
}
This returns values like "+01:30" or "-05:00". You can extract the numeric values from my example if needed to do calculations.
Note that getTimezoneOffset() returns a the number of minutes difference from UTC, so that value appears to be opposite (negated) of what is needed for formats like ISO 8601. Hence why I used Math.abs() (which also helps with not getting negative minutes) and how I constructed the ternary.
I highly recommend using the moment.js library for time and date related Javascript code.
In which case you can get an ISO 8601 formatted UTC offset by running:
> moment().format("Z")
> "-08:00"
<script type="text/javascript">
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
</script>

get date string from utc unixtime and add a timezone offset

I would like to generate in JS a Date object (or XDate) starting from a UTC unix timestamp, add a timezone offset and then generate a String in the format "yyyy-MM-dd HH:mm:ss".
For now I did this:
createServerRelativeTs : function(unixtimeutc, utcoffset) {
var stimeUTCoffset = (isNaN(utcoffset)) ? 1 : utcoffset;
var time = new XDate(Math.round(unixtimeutc * 1000));
var hours = time.getUTCHours() + stimeUTCoffset;
time.setUTCHours(hours);
return time.toString("yyyy-MM-dd HH:mm:ss");
}
in which utcoffset is a integer number and unixtimeutc is a unixtimestamp
The problem with this code is that If I change the timezone in my OS the result changes! If I add the offset value to the timestamp it gets ignored. How can I get a OS-timezone-independent result?
This is really a combination of a few answers. You need to work in UTC to avoid the effects of the host timezone which is considered when using non-UTC methods.
So create a Date from the UNIX time value, adjust the UTC minutes for the offset, then format the output string using UTC methods as local.
This might be a bit simpler with a library, but it's not really necessary.
/* Given a Date, return a string in //yyyy-MM-dd HH:mm:ss format
** #param {Date} d
** #returns {string}
*/
function formatISOLocal(d) {
function z(n){return (n<10?'0':'')+n}
if (isNaN(d)) return d.toString();
return d.getUTCFullYear() + '-' +
z(d.getUTCMonth() + 1) + '-' +
z(d.getUTCDate()) + ' ' +
z(d.getUTCHours()) + ':' +
z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) ;
}
/* Adjust time value for provided timezone
** #param {Date} d - date object
** #param {string} tz - UTC offset as +/-HH:MM or +/-HHMM
** #returns {Date}
*/
function adjustForTimezone(d, tz) {
var sign = /^-/.test(tz)? -1 : 1;
var b = tz.match(/\d\d/g); // should do some validation here
var offset = (b[0]*60 + +b[1]) * sign;
d.setUTCMinutes(d.getUTCMinutes() + offset);
return d;
}
// Given a UNIX time value for 1 Jan 2017 00:00:00,
// Return a string for the equivalent time in
// UTC+10:00
// 2017-01-01T00:00:00Z seconds
var n = 1483228800;
// Create Date object (a single number value is treated as a UTC time value)
var d = new Date(n * 1000);
// Adjust to UTC+10:00
adjustForTimezone(d, '+10:00');
// Format as local string
console.log(formatISOLocal(d))

How to get the exact local time of client?

What is the best method to get the clients local time irrespective of the time zone of clients system? I am creating an application and i need to first of all get the exact time and date of the place from where the client is accessing. Even detecting the ip address of client system has a drawback or detecting the time zone of client system may be risky at times. So, is there any way out which could be really reliable and not vulnerable to error because displaying wrong time and date to client is something very embarassing.
In JavaScript? Just instantiate a new Date object
var now = new Date();
That will create a new Date object with the client's local time.
Nowadays you can get correct timezone of a user having just one line of code:
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions
You can then use moment-timezone to parse timezone like:
const currentTime = moment().tz(timezone).format();
Try
let s= new Date().toLocaleString();
console.log(s);
If you want to know the timezone of the client relative to GMT/UTC here you go:
var d = new Date();
var tz = d.toString().split("GMT")[1].split(" (")[0]; // timezone, i.e. -0700
If you'd like the actual name of the timezone you can try this:
var d = new Date();
var tz = d.toString().split("GMT")[1]; // timezone, i.e. -0700 (Pacific Daylight Time)
UPDATE 1
Per the first comment by you can also use d.getTimezoneOffset() to get the offset in minutes from UTC. Couple of gotchas with it though.
The sign (+/-) of the minutes returned is probably the opposite of what you'd expect. If you are 8 hours behind UTC it will return 480 not -480. See MDN or MSDN for more documentation.
It doesn't actually return what timezone the client is reporting it is in like the second example I gave. Just the minutes offset from UTC currently. So it will change based on daylight savings time.
UPDATE 2
While the string splitting examples work they can be confusing to read. Here is a regex version that should be easier to understand and is probably faster (both methods are very fast though).
If you want to know the timezone of the client relative to GMT/UTC here you go:
var gmtRe = /GMT([\-\+]?\d{4})/; // Look for GMT, + or - (optionally), and 4 characters of digits (\d)
var d = new Date().toString();
var tz = gmtRe.exec(d)[1]; // timezone, i.e. -0700
If you'd like the actual name of the timezone try this:
var tzRe = /\(([\w\s]+)\)/; // Look for "(", any words (\w) or spaces (\s), and ")"
var d = new Date().toString();
var tz = tzRe.exec(d)[1]; // timezone, i.e. "Pacific Daylight Time"
In order to get local time in pure Javascript
use this built in function
// return new Date().toLocaleTimeString();
See below example
function getLocaltime(){
return new Date().toLocaleTimeString();
}
console.log(getLocaltime());
directly like this :
new Date((new Date().setHours(new Date().getHours() - (new Date().getTimezoneOffset() / 60)))).toISOString()
more details in this utility function
function getLocaLTime() {
// new Date().getTimezoneOffset() : getTimezoneOffset in minutes
//for GMT + 1 it is (-60)
//for GMT + 2 it is (-120)
//..
let time_zone_offset_in_hours = new Date().getTimezoneOffset() / 60;
//get current datetime hour
let current_hour = new Date().getHours();
//adjust current date hour
let local_datetime_in_milliseconds = new Date().setHours(current_hour - time_zone_offset_in_hours);
//format date in milliseconds to ISO String
let local_datetime = new Date(local_datetime_in_milliseconds).toISOString();
return local_datetime;
}
Just had to tackle this so thought I would leave my answer. jQuery not required I used to update the element as I already had the object cached.
I first wrote a php function to return the required dates/times to my HTML template
/**
* Gets the current location time based on timezone
* #return string
*/
function get_the_local_time($timezone) {
//$timezone ='Europe/London';
$date = new DateTime('now', new DateTimeZone($timezone));
return array(
'local-machine-time' => $date->format('Y-m-d\TH:i:s+0000'),
'local-time' => $date->format('h:i a')
);
}
This is then used in my HTML template to display an initial time, and render the date format required by javascript in a data attribute.
<span class="box--location__time" data-time="<?php echo $time['local-machine-time']; ?>">
<?php echo $time['local-time']; ?>
</span>
I then used the getUTCHours on my date object to return the time irrespective of the users timezone
The getUTCHours() method returns the hour (from 0 to 23) of the
specified date and time, according to universal time.
var initClocks = function() {
var $clocks = $('.box--location__time');
function formatTime(hours, minutes) {
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
return {
hours: hours,
minutes: minutes
}
}
function displayTime(time, $clockDiv) {
var currentTime = new Date(time);
var hours = currentTime.getUTCHours();
var minutes = currentTime.getUTCMinutes();
var seconds = currentTime.getUTCSeconds();
var initSeconds = seconds;
var displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
setInterval(function() {
if (initSeconds > 60) {
initSeconds = 1;
} else {
initSeconds++;
}
currentTime.setSeconds(initSeconds);
hours = currentTime.getUTCHours();
minutes = currentTime.getUTCMinutes();
seconds = currentTime.getUTCSeconds();
displayTime = formatTime(hours, minutes);
$clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);
}, 1000);
}
$clocks.each(function() {
displayTime($(this).data('time'), $(this));
});
};
I then use the setSeconds method to update the date object based on the amount of seconds past since page load (simple interval function), and update the HTML
The most reliable way I've found to display the local time of a city or location is by tapping into a Time Zone API such as Google Time Zone API. It returns the correct time zone, and more importantly, Day Light Savings Time offset of any location, which just using JavaScript's Date() object cannot be done as far as I'm aware. There's a good tutorial on using the API to get and display the local time here:
var loc = '35.731252, 139.730291' // Tokyo expressed as lat,lng tuple
var targetDate = new Date() // Current date/time of user computer
var timestamp = targetDate.getTime() / 1000 + targetDate.getTimezoneOffset() * 60 // Current UTC date/time expressed as seconds since midnight, January 1, 1970 UTC
var apikey = 'YOUR_TIMEZONE_API_KEY_HERE'
var apicall = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + loc + '&timestamp=' + timestamp + '&key=' + apikey
var xhr = new XMLHttpRequest() // create new XMLHttpRequest2 object
xhr.open('GET', apicall) // open GET request
xhr.onload = function() {
if (xhr.status === 200) { // if Ajax request successful
var output = JSON.parse(xhr.responseText) // convert returned JSON string to JSON object
console.log(output.status) // log API return status for debugging purposes
if (output.status == 'OK') { // if API reports everything was returned successfully
var offsets = output.dstOffset * 1000 + output.rawOffset * 1000 // get DST and time zone offsets in milliseconds
var localdate = new Date(timestamp * 1000 + offsets) // Date object containing current time of Tokyo (timestamp + dstOffset + rawOffset)
console.log(localdate.toLocaleString()) // Display current Tokyo date and time
}
} else {
alert('Request failed. Returned status of ' + xhr.status)
}
}
xhr.send() // send request
From: Displaying the Local Time of Any City using JavaScript and Google Time Zone API
I found this function is very useful during all of my projects. you can also use it.
getStartTime(){
let date = new Date();
var tz = date.toString().split("GMT")[1].split(" (")[0];
tz = tz.substring(1,5);
let hOffset = parseInt(tz[0]+tz[1]);
let mOffset = parseInt(tz[2]+tz[3]);
let offset = date.getTimezoneOffset() * 60 * 1000;
let localTime = date.getTime();
let utcTime = localTime + offset;
let austratia_brisbane = utcTime + (3600000 * hOffset) + (60000 * mOffset);
let customDate = new Date(austratia_brisbane);
let data = {
day: customDate.getDate(),
month: customDate.getMonth() + 1,
year: customDate.getFullYear(),
hour: customDate.getHours(),
min: customDate.getMinutes(),
second: customDate.getSeconds(),
raw: customDate,
stringDate: customDate.toString()
}
return data;
}
this will give you the time depending on your time zone.
Thanks.
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
I needed to report to the server the local time something happened on the client. (In this specific business case UTC provides no value). I needed to use toIsoString() to have the format compatible with .Net MVC but toIsoString() this always converts it to UTC time (which was being sent to the server).
Inspired by the 'amit saini' answer I now use this
function toIsoStringInLocalTime(date) {
return new Date((date.getTime() + (-date.getTimezoneOffset() * 60000))).toISOString()
}
You can also make your own nodeJS endpoint, publish it with something like heroku, and access it
require("http").createServer(function (q,r) {
r.setHeader("accees-control-allow-origin","*")
r.end(Date.now())
}).listen(process.env.PORT || 80)
Then just access it on JS
fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))
This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3 milliseconds to Date.now() to add 3 hours)
For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side
In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..
EDIT
just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client
require("http").createServer(function (q,r) {
var d= new Date()
r.setHeader("accees-control-allow-origin","*")
r.setHeader("zman", d.toString())
r.end(d.getTime())
}).listen(process.env.PORT || 80)
new Date(Date.now() + (-1*new Date().getTimezoneOffset()*60000)).toISOString()
my code is
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
<body onload=display_ct();>
<span id='ct' ></span>
</body>
Try on this way
function timenow(){
var now= new Date(),
ampm= 'am',
h= now.getHours(),
m= now.getMinutes(),
s= now.getSeconds();
if(h>= 12){
if(h>12) h -= 12;
ampm= 'pm';
}
if(m<10) m= '0'+m;
if(s<10) s= '0'+s;
return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
toLocaleDateString()
is a function to change the date time format like toLocaleDateString("en-us")

Categories