Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I am able to successfully convert timestamp to datetime using below code:

Timestamp to DateTime:
C#
double dTimeSpan = Convert.ToDouble("1404757800000");
DateTime dtReturn = new DateTime(1970, 1, 1, 0, 0, 0,    DateTimeKind.Utc).AddSeconds(Math.Round(dTimeSpan / 1000d)).ToLocalTime();


Result:
C#
7/8/2014 12:00:00 AM



But i am not able to convert this datetime to correct timestamp. Using below code because it give me wrong timestamp.

Datetime to Timestamp:
C#
DateTime dtEPoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime dtTime = dtReturn.Subtract(new TimeSpan(dtEPoch.Ticks));
long lngTimeSpan = dtTime.Ticks / 10000;
string strTimeSpan = lngTimeSpan.ToString();



Result:
C#
1404777600000




Please suggest me.
Posted
Updated 30-Jun-14 0:30am
v3

Try this
C#
 date=new Datetime(2014,8,7);
long Timestamp = date.Ticks - new DateTime(1970, 1, 1).Ticks;
    Timestamp /= TimeSpan.TicksPerSecond;
    return Timestamp;
 
Share this answer
 
v2
I think this should do the trick.

C#
DateTime dtEPoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = dtReturn - dtEPoch;
string strTimeSpan = timeSpan.ToString();
 
Share this answer
 
Change DateTimeKind.Utc to DateTimeKind.Local then it will work
double dTimeSpan = Convert.ToDouble("1404757800000");
      DateTime dtReturn = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds(Math.Round(dTimeSpan / 1000d)).ToLocalTime();

      DateTime dtEPoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local);
      DateTime dtTime = dtReturn.Subtract(new TimeSpan(dtEPoch.Ticks));
      long lngTimeSpan = dtTime.Ticks / 10000;
      string strTimeSpan = lngTimeSpan.ToString();

Get more details Here[^]
 
Share this answer
 
v2
Comments
Harish Kumar Bansal 30-Jun-14 7:10am    
Thanks, it is working fine by changing Utc to Local.
C#
DateTime oDT = new DateTime(2014, 2, 21);
TimeSpan oTS = new TimeSpan(oDT.Ticks);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900