Converting a datetime into UTC with Javascript - javascript

Ok, so I'm writing a Titanium app that digests a JSON feed and adds events to the users calendar. The problem I'm facing is that the JSON feed will have the datatime in local time (including daylight savings where appropriate), and the calendar needs UTC.
One simplification is the event is always in the same location (London), so the only real issue is allowing for DST (BST). So if I'm getting a date string like 2014-04-27 19:00:00 from the feed, what's the best way to get that into a javascript date object in UTC (which I think, in this case, would look like 2014-04-27T18:00:00Z, but it all depends on the time of year).

If you're okay with bringing in a library, Momentjs with the Timezone plugin are able to do this...
var input = '2014-04-27 19:00:00';
var eventDateInUtc = moment.tz(input, 'Europe/London').utc();
var output = eventDateInUtc.toDate().toISOString(); // '2014-04-27T18:00:00.000Z'
JSFiddle

Try this hope it will help you
var newDate = new Date();
var newDateUTC = new Date(newDate.getUTCFullYear(), newDate.getUTCMonth(), newDate.getUTCDate(), newDate.getUTCHours(), newDate.getUTCMinutes(), newDate.getUTCSeconds());

Related

Foreign Time to Local Time

I'm trying to convert foreign time to Local Time. I'm getting a date and time in Europe/London. Currently I'm using moment-timezone to get my code working, however its giving me a wrong output.
resultDate = new moment('2017-06-30T22:10:00').tz('Europe/London').format('YYYY-MM-DD HH:mm:ss');
I think the code thinks that the date input is already in local time where I need to convert it into Europe/London which would give a local result, where as what I want is to actually convert the foreign time to local time.
In short the date and time as my input (2017-06-30T22:00:00), I am expecting it to be 7 hours in advance (2017-07-1T05:00:00) since I currently live in Asia/Manila, 7 hours in advance to London. However I'm getting 2017/06/30 15:00:00 +0100 as my result.
Is there a way for me to do this by utilizing the information 'Europe/London' or 'Asia/Manila' as seen in my code?
You can use moment.tz to parse your input as Europe/London time and then use the tz function to convert it to Asia/Manila.
The first parses your input using the given timezone while the latter convert a moment objet to a given timezone.
Here a working sample:
// Parse input considering as London tz
var timeInLondon = moment.tz('2017-06-30T22:10:00', 'Europe/London');
// Converting input to Manila
var timeInManila = timeInLondon.tz('Asia/Manila');
// Show result
console.log(timeInManila.format('YYYY-MM-DD HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data-2010-2020.min.js"></script>

Moment.js transform to date object

Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.
Example:
var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.
You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().
Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().
Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:
momentObj.format("YYYY-MM-DD HH:mm:ss")
Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.
A couple of other little things:
While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.
Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.
.toDate did not really work for me, So, Here is what i did :
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
Since momentjs has no control over javascript date object I found a work around to this.
const currentTime = new Date();
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");
const convertTimeObject = new Date(convertTime);
This will give you a javascript date object with the converted time
The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
const moment=require('moment-timezone')//import from moment-timezone
Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.
To convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();
nice and clean!!!!
I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString(); but then I started getting errors about feeding that string back into moment.
I tried the moment.tz(dateStr, 'America/New_York').toDate(); but then I lost timezone information which I needed.
The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();
try (without format step)
new Date(moment())
var d = moment.tz("2019-04-15 12:00", "America/New_York");
console.log( new Date(d) );
console.log( new Date(moment()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
moment has updated the js lib as of 06/2018.
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.
new Date(moment()) - could give error while exporting the data column in excel
use
moment.toDate() - doesn't give error or make exported file corrupt

Need help to resolve the issue when converting epoch date to human readable format - Javascript

My java script application uses .net web service to get the data from back end. Everything works fine except for date / time conversion. I need to convert the epoch date returned by service to user's local browser date.
The web service returns date in the below format,
/Date(1335341422660-0500)/
This is what I have done to convert this to human readable date,
I strip out everything after hyphen (-) and use the remaining data for date conversion
var dateVal=dateField.replace(/-.*\)/g,')');
var date = new Date(parseFloat(dateVal.substr(6)));
var dateArray=date.toString().split(" ");
if(dateArray.length>3){
timeZone=("("+dateArray[4])+")"
}
var month=date.getMonth() + 1;
var year=date.getFullYear();
var date=date.getDate();
var hours= date.getHours();
var offset=date.getTimezoneOffset();
var finalDateStr=(year+"-"+month+"-"+dateValue)+" "+hours+":"+
minutes+":"+seconds+" "+timeZone;
For the above epoch value, expected date is,
4/24/2012 9:10:22 PM - This date is displayed in a .net application which is actually the source application that inserts this date in to MS SQL server whenever a new item is created / updated. They convert the SQL server date to local date (using .net) and display it in UI.
but when I form the date using the above script I am getting the value as,
2012-4-25 4:10:22 (EDT) (7 hours more compared to above date).
I am not sure where I am wrong.. Can some one help me figure out this issue?
For such date manipulations, you might want to consider using Moment.js.
Not sure if this is a great way to fix this issue...
This is what I did and seems to work fine... Again I dont think this is a fool proof solution but I checked in various time zones (with / without daylight saving time) and it seems to work......
var dateVal=dateField.replace(/-.*\)/g,')');
var date = new Date(parseFloat(dateVal.substr(6)));
var dateArray=date.toString().split(" ");
var timeZone="(Local Time)";
if(dateArray.length>3){
timeZone=("("+dateArray[4])+")"
}
var date2=dateField.split("-");
var dateOffset=(date2[1].toString().replace(")","").replace("/",""));
if( date.toString().toUpperCase().indexOf("DT")!==-1){
date.setHours(date.getHours()-(parseFloat(parseFloat(dateOffset).toString().replace(/0*$/, ''))+2));
}else{
date.setHours(date.getHours()-(parseFloat(parseFloat(dateOffset).toString().replace(/0*$/, ''))+1));
}
var month=date.getMonth() + 1;
var year=date.getFullYear();
var dateValue=date.getDate();
var hours= date.getHours();
var minutes= date.getMinutes();
var seconds=date.getSeconds()
var finalDateStr=(year+"-"+month+"-"+dateValue)+" "+hours+":"+
minutes+":"+seconds+" "+timeZone;

Java Script: How to ammend a datetime variable to set a specific time?

I need to take a datetime values from an MSSQL based app which is read into the script as 22/12/2010 3:56pm and adjsut the time component toa set time.
I've used what I know of javascript and what I can find in google searches to try and progress this but to no avail.
Premis: I need to read the date time value and set the time portion of the date to 8am, 1pm or 4pm dependent on another field.
The conditional logic portion of the script is fine the date functions aren't so fine.
Current code I'm currently using:
if(fldPriority.Value=='2')
{
var ResDate = new Date(fldTargetResolutionTime.Value);
var newdate = new Date(ResDate.getYear(),ResDate.GetMonth(),ResDate.GetDay(),16,0,0,0);
objReturn = newdate
}
Problem:
The date reads in originally in gmt format 22/12/2010 3:56pm but then gets changes to utc format and the date changes significantly to Wed Oct 12 15:56:00 UTC+12 2011
Any help would be greatly appreciated.
Make a copy of the Date and set the time using UTCHours.
The return value will be the correct Date and time,
but you if need to convert it to a string the string will be local time unless you call newDate.toUTCString();
(or objReturn.toUTCString())
var newdate=new Date(ResDate);
newDate.setUTCHours(16,0,0,0);
objReturn=newDate;

How to get difference of saved time and current time in jquery?

I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)

Categories

Resources