Reputation: 6362
On the server I am using Yahoo API for getting currencies http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDGBP=X,USDEUR=X
in the result I am getting Date
and Time
and would like to convert it to DateTime
Object so I can later convert it to Local time for the clients
I did it with the following
DateTime d = dateOnly.Add(timeOnly.TimeOfDay);
I now want to convert it to Local Time on the clients (Javascript)
I tried on the client
var d = new Date(d + " UTC");
alert(d.toString());
Edit d value is 2015-04-06T12:32:00
but getting error Invalid Date
Upvotes: 1
Views: 1400
Reputation: 241693
Simply change your code to form an ISO 8601 string correctly.
var d = new Date(d + "Z");
Screenshot from Chrome debug console:
Alternatively, you could ensure the Z
was added by your .NET code by making sure the .Kind
of your DateTime
value was set to DateTimeKind.Utc
.
For example:
d = DateTime.SpecifyKind(d, DateTimeKind.Utc);
Or better yet, you can just parse it as UTC to begin with.
string dateOnly = "4/6/2015";
string timeOnly = "11:32pm";
DateTime dt = DateTime.ParseExact(dateOnly + " " + timeOnly,
"M/d/yyyy h:mmtt",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
This is probably the safest way. Now the kind will already be UTC, and the Z
will already be in place.
Upvotes: 1
Reputation: 6580
Try this... I am assuming Yahoo CSV is in US format (m/d/yyyy)... If not, you need to fix the how the month and date are extracted in fixYahooDate...
(function() {
'use strict';
String.prototype.pad = function(c, l) {
return (new Array(l + 1).join(c) + this).substr(-l, l);
};
function fixYahooDate(aDate) {
var match = /(\d?\d)\/(\d?\d)\/(\d+)/gi.exec(aDate);
var m = match[1];
var d = match[2];
var y = match[3];
var sm = m.pad('0', 2);
var sd = d.pad('0', 2);
var fixedDate = sm + "/" + sd + "/" + y;
return fixedDate;
}
function fixYahooTime(aTime) {
var match = /(\d?\d):(\d\d)(am|pm)/gi.exec(aTime);
var h = match[1];
var m = match[2];
var a = match[3];
var sh = h.pad('0', 2);
var fixedTime = sh + ":" + m + ":00 " + a + " UTC";
return fixedTime;
}
function YahooDateTimeToLocal(aDate, aTime) {
var s = fixYahooDate(aDate) + " " + fixYahooTime(aTime);
console.log(s);
var dt = new Date(s);
return dt;
}
var aDate = "4/6/2015";
var aTime = "12:29pm";
var localDt = YahooDateTimeToLocal(aDate, aTime);
console.log(localDt.toString());
}());
Upvotes: 0