Reputation: 378
what is good way to convert Epoch time to date, but using specific timezone
I need to check two dates. One date i have in database and another in x website.
I know that both dates are exactly the same in relation of yyyy-MM-dd
in example:
Database date is: 1398891600 = 2014-05-01
X Website date is: 1398902400000 = 2014-05-01
C# code "converter"
private string DateChecker_inEPOCH(string epochdate)
{
if (epochdate.Length < 13)
{
epochdate = epochdate + "000";
}
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(epochdate));
string dateFormated = dt.ToString("yyyy-MM-dd");
return dateFormated;
}
Issue is that when i convert using my method one db date is 2014-04-30 and website date is 2014-05-01.
I tested dates using http://www.epochconverter.com/
Upvotes: 1
Views: 5623
Reputation: 491
Database date is: 1398891600 = 2014-05-01
X Website date is: 1398902400000 = 2014-05-01
EpochConverter.com gives me the following results:
1398891600000 -> Wed, 30 Apr 2014 21:00:00 GMT
1398902400000 -> Thu, 01 May 2014 00:00:00 GMT
So your code seems to be consistent with EpochConverter.com.
With regards to timezones, I would make sure all dates are stored/retrieved using UTC. This will save you a lot of headaches when it comes to converting to/from different timezones. In this case, assuming the epoch was stored relative to a UTC date, you would simply do the following:
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Convert.ToDouble(epochdate));
You can then use the following if you need to display a local time to the end user:
utcDate.ToLocalTime();
Upvotes: 7