Handling different timezone to get data from db in javascript [duplicate] - javascript

This question already has answers here:
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 9 years ago.
I have pcap import and read facility in my project. I have handling timezone in my project. Imported pcap is not read/display if I changed my timezone from GMT to other Asia/Kolkota.
How can I handle timezone issue in javascript. I am storing the value into the database is 2013-05-07 00:04:23.435751-06.
it should be handled in all timezone. thanks in advance

I wish you are looking for this beautiful documentation. Thanks.
Update
try this:
var str= '2013-05-07 00:04:23.435751-06';
var n = str.slice( -3 );
var time = str.replace(" ","T");
time = time.slice(0, -3);
alert(calcTime(time, n));
function calcTime(time, offset) {
// create Date object for current location
d = new Date(Date.parse(time));
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The Time is " + nd.toLocaleString();
}

Related

Convert UTC time into IST time in node js [duplicate]

This question already has answers here:
Generating a date in a particular timezone [duplicate]
(2 answers)
Converting unix date-timestamp to time for a particular timezone in javascript
(2 answers)
Closed 5 years ago.
I have UTC time 1502212611. I have to convert it to 2017-08-08 17:16:51. But when I use the code below I am getting 2017-08-08T17:16:51.000Z.
var utc = 1502212611;
var utcSeconds = utc;
var d = new Date(0);
d.setUTCSeconds(utcSeconds);
console.log(d);
You can use moment.js, as others have already suggested.
But in your question is not clear if you want the output as UTC or IST (the question title says "Convert UTC to IST", but in the question the desired output (2017-08-08 17:16:51) is the corresponding UTC date/time).
Anyway, if you want the output in UTC, you can do this:
var utc = 1502212611;
var m = moment.unix(utc).utc().format('YYYY-MM-DD HH:mm:ss');
console.log(m);
The unix method takes a value of seconds since epoch (1970-01-01T00:00Z). Then the utc() method makes sure the date will be formatted as UTC (if you don't call it, the date will be displayed using the default timezone, which can vary according to your system).
The output will be:
2017-08-08 17:16:51
If you need to convert to IST, you'll need to also use moment timezone:
var utc = 1502212611;
var m = moment.unix(utc).tz('Asia/Kolkata').format('YYYY-MM-DD HH:mm:ss');
console.log(m);
The tz method converts the date to another timezone. The rest of the code is similar to the previous one.
The output will be:
2017-08-08 22:46:51
Note that I used Asia/Kolkata instead of IST. That's because the API uses IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard - IST can be "India Standard Time", "Israel Standard Time" or "Irish Standard Time", and the API can't deal with such ambiguity (the code above won't work with IST, so you must use a proper timezone name).
You can get a list of all available timezones names (and choose the one that fits best to your case) by calling moment.tz.names().
In plain Javascript, you must do it manually:
// pad zero if value <= 9
function pad(value) {
return value > 9 ? value: "0" + value;
}
var utc = 1502212611;
var d = new Date(0);
d.setUTCSeconds(utc);
var m = d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate())
+ ' ' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes())+ ':' + pad(d.getUTCSeconds());
console.log(m);
Output:
2017-08-08 17:16:51
You can use moment if you have a moment .
momenttime = moment()
momenttime.format("YYYY-MM-DD hh:mm:ss ")

How do I get difference between two dates of unknown format in javascript?

I get a date as String from server like this: 2017-01-23T16:08:45.742Z. I want to find the difference in days, between this and the current date (or precisely, current time). I could just extract date alone (without time) and check, but I'd need a precise answer based on provided time & current time.
How do I achieve this?
Should be easy....
var dateFromServer = '2017-01-23T16:08:45.742Z'
var msInDay = 1000 * 60 * 60 * 24
var difference = (new Date(dateFromServer) - Date.now()) / msInDay
document.write('difference = ' + difference + ' days')
That date format looks like ISO_8061. https://en.wikipedia.org/wiki/ISO_8601
Use the Date object to get the difference between today and the other date in milliseconds, then divide by the number of milliseconds in a day.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
The code below can be condensed into a single line but I wanted to be explicit.
let date = "2017-01-23T16:08:45.742Z";
let d1 = new Date(date); // given date
let today = new Date(); // today's date
let diff = (d1 - today); // difference in milliseconds
let days = diff / 8.64e+7; // divide difference by 1 day in milliseconds
console.log(days)
Point of clarification: if I understand you correctly, you're actually trying to get the difference between two dates of different formats, not two dates of unknown formats. That's way easier.
Further, it looks like your server string is already stored in ISO format, which again makes this way easier.
I'd recommend looking at the JavaScript Date object. I believe in this case your best bet would be something like this:
// Your string from the server
var data_from_server = '2017-01-23T16:08:45.742Z';
// Create a new Date() object using the ISO string provided by your server
var olddate = new Date(data_from_server);
// Create a new empty Date() object, which should default to the current time
var currentdate = new Date();
// Subtract the two
var dif = currentdate.getTime() - olddate.getTime();
// Alert the result
alert(dif);

format datetime specific timezone

I am using globalize to format datetime per locale.
var Globalize = require('globalize');
var formatter = Globalize('en-US').dateFormatter();
formatter(new Date());
It works great but I was wondering if I can format date for specific timezone. This way, it always formats date in the local machine timezone.
For example, let's say my machine timezone is PST. Can I use globalize to format date in EST?
Stolen from here
This solution works by using the getTimeOffset() (which returns the time difference between UTC time and local time, in minutes) function to find the UTC time offset of a given location and changing it to milliseconds, then performing calculations from UTC to return a time for a different time zone.
/**
* function to calculate local time
* in a different city
* given the city's UTC offset
*/
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
This solution will work, but it's simpler to express timezone in minutes and adjust the UTC minutes.
Please let me know if this works for you!
The javascript function new date() generates a date/time stamp based off the machine time at the moment that the function was called. So if the function is called by a machine that is in Alaska, it will generate a date/time stamp based on the current time in Alaska at that exact moment.
w3school.com has great references to most coding related items. You can find the answer to your question here.

Add 5 days to the current date using JavaScript [duplicate]

This question already has answers here:
How to add number of days to today's date? [duplicate]
(16 answers)
Closed 9 years ago.
I am trying to add 5 days to today's date using JavaScript. I am also trying to add this function into a button so that the result comes in an alert box when I click it, not as soon as I open the page.
I am new to JavaScript and trying very hard to learn.
Any help?
Thanks!
Declare a Date variable (it will be set to current date/time):
var dt = new Date();
Add 5 days:
dt.setDate(dt.getDate() + 5);
Put all the above in your click handler function. Something like:
document.getElementById('dateBtn').onclick = function () {
var dt = new Date();
dt.setDate(dt.getDate() + 5);
alert(dt);
};
FIDDLE EXAMPLE
var date = new Date(); // Get current Date
date.setDate(date.getDate()+5); // add 5 days to the current date
For more information see Date.
Might be overkill but moment.js could be useful to you.
JavaScript stores dates and times in milliseconds. So, add 5 days worth:
var fiveDaysLater = new Date(0,0,0,0,0,0,Date.now() + 5 * 24 * 60 * 60 * 1000);
Date.now() returns a value in milliseconds.
The date constructor (new Date) then makes a new Date object (hence the keyword new) using this value, plus the five days of milliseconds, and initializes the variable fiveDaysLater.
create a Date instance five days:
var fiveDaysLater = new Date( AnyYourDate.getTime() );
fiveDaysLater.setDate(fiveDaysLater.getDate() + 5);

new Date(UTCstrings), convert an UTCStrings to other timezone (not local)

I know how to use new Date(UTCStrings) to local timezone.
But now, the question is how to convert an UTCString to other timezone (not local).
e.g.
The UTCString is '1338480000000'.
My local timezone is UTC+4.
I want to convert the date(UTCString) to UTC+9.
How can I do it?
Appreciate for your help!
Update
Thanks for BalaKrishnan's help.
I follow BalaKrishnan's key points maked a simple function. Hopefully, this will help others.
function utcToOtherTimezone(utcString, timezone){
var isoDt = new Date(utcString), // do this to convert it to iso time:
dt = isoDt.addMinutes( isoDt.getTimezoneOffset() + (timezone * 60) );
return dt.toLocaleDateString() + ' ' + dt.toLocaleTimeString();
}
$('#dtime').html(utcToOtherTimezone(1341282169000, +8));​
And don't forget to add datejs
Online testing example http://jsfiddle.net/ysjia/FWbZ8/. Enjoy it.
First create a Date object from the UTCString as follows:
var utcString = 1338480000000;
// This will however be in local time, not iso time.
var isoDt = new Date(utcString);
// do this to convert it to iso time:
isoDt.addMinutes( isoDt.getTimezoneOffset()
);
// addMinutes is an API from Date.js.
Now the isoDt object has it's date value the same as the UTC date, to which you can add the necessary offset +9 or whatever.
Refer to this jquery faq that discusses this:
http://jqfaq.com/how-to-parse-a-date-string-disregarding-time-zones/

Categories