17

I'm getting timestamp from xml document.Now, I want to convert Timestamp to Date format(13-May-13)

XmlNodeList cNodes = xncomment.SelectNodes("comment");
foreach (XmlNode node in cNodes)
{
    //I'm getting this "1372061224000" in comment-date
    string comment_date = node["creation-timestamp"].InnerText;
}

Any ideas? Thanks in advance.

Kjartan
  • 18,591
  • 15
  • 71
  • 96
user2500094
  • 1,033
  • 6
  • 23
  • 42

5 Answers5

34

Given that this looks like a Java timestamp, simply use below:

var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Math.Round(1372061224000 / 1000d)).ToLocalTime();
Console.WriteLine(dt); // Prints: 6/24/2013 10:07:04 AM
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
9

Finally i found how to convert time stamp to Date & Date to time stamp . I found some places in project people keep date as time stamp for get difference quickly. so in this case they use to keep the table column as Int or time stamp. now the problem is that in the application while showing the data, you need to convert it into date variable. So for that we can use the following code to convert time stamp to Date

int ts = 1451174400;
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(ts).ToLocalTime();
string formattedDate = dt.ToString("dd-MM-yyyy");

Now you can get any date format from this variable.

In the second case if you want to convert Date to time stamp then check the following code.

int ts = (dt.Ticks - 621356166000000000) / 10000000;

Where dt is the date time variable & holding a date value.

Sapnandu
  • 620
  • 7
  • 9
2

Maybe replace this :

    foreach (XmlNode node in cNodes)
{
    //I'm getting this "1372061224000" in comment-date
    string comment_date = node["creation-timestamp"].InnerText;
}

by :

foreach (XmlNode node in cNodes)
{
    Datetime comment_date = new DateTime(Convert.ToInt32(node["creation-timestamp"]);
}
1

Thanks to all.

Finally I got the output

foreach (XmlNode node in cNodes)
{
    comment_timestamp = node["creation-timestamp"].InnerText;
    DateTime comment_date1 = new DateTime(Convert.ToInt64(comment_timestamp));
    comment_date = Convert.ToDateTime(comment_date1).ToString("dd-MMM-yy");
}

Output:

01-MAY-13
FoggyFinder
  • 2,230
  • 2
  • 20
  • 34
user2500094
  • 1,033
  • 6
  • 23
  • 42
0

You can use FromUnixTimeSeconds method of DateTimeOffset

 var dateTime1 = new DateTime(2020, 4, 5, 12, 15, 12);//05.04.2020 12:15:12

 var timeStamp = new DateTimeOffset(dateTime1).ToUnixTimeSeconds(); //1586074512

If FromUnixTimeSeconds's result is not corresponding your original datetime, you can use LocalDateTime property of DateTimeOffset object.

 var dateTime2 = DateTimeOffset.FromUnixTimeSeconds(timeStamp).DateTime;//05.04.2020 08:15:12
 var dateTime3 = DateTimeOffset.FromUnixTimeSeconds(timeStamp).LocalDateTime;//05.04.2020 12:15:12

For more information please visit this link DateTimeOffset.FromUnixTimeSeconds(Int64) Method

Ramil Aliyev 007
  • 4,437
  • 2
  • 31
  • 47