0

I'm trying to display a timeago that a question has been asked in my project. In my database I have a Datetime columns 'listed'. When a user posts a question I insert the question with the UTC DateTime.

In the client I have both Livestamp.js and moment.js to display the timeago the question has been asked.

Code:

var then = moment(listed).unix(); // convert to unix time

and then:

s += "</td><td><span data-livestamp='" + then + "'></span>";

The problem is that it doesn't shows the timeago as intended, more hours back.

Example of returned date string from server:

2015-03-09T09:16:41

I need a way for livestamp to show the timeago considering UTC Time based on the datetime from the server and taking into consideration the local UTC time, but I don't know how to achieve this.

Note: the server doesn't reside in the same location as the clients (visitors), quite obviously.

Using: MySQL, .NET/C# 4.5, jQuery/Javascript

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Liron Harel
  • 10,819
  • 26
  • 118
  • 217

1 Answers1

2

I had a similar issue two year ago and, here is how I solved it:

var localtime = new Date(new Date(listed).getTime() - 
                (new Date().getTimezoneOffset() * 60000));


 var then = moment(localtime).unix(); 

EDITS: Tried this

  var localDate = new Date(new Date('2015-03-09T13:56:41').getTime() -
                            (new Date().getTimezoneOffset() * 60000));


var then = moment(localDate).unix(); 
document.getElementById("demo").innerHTML = 
              "Made it : <span data-livestamp='" + then + "'></span>" ;

   //Results: "Made it : 5 minutes ago" as I'm in a +1 timezone
Bellash
  • 7,560
  • 6
  • 53
  • 86
  • It shows "in 25 minutes ago" instead of "2 hours ago". – Liron Harel Mar 09 '15 at 11:07
  • I have tried it myself and it works: with a date string! If you get a wrong livestamp this may be because of offset between your database and application server. Please check if the `listed` remains the same between database and application servers and inspect it in your browser. – Bellash Mar 09 '15 at 14:01
  • The date being created is +2 hours as in my +2 timezone. Which means that the localdate is set to 10:00 when my time is actually 8:00. That's what I see "in 2 hours" (in the future) in the results. The time is listed correctly when I do moment.utc(listed).toDate(); and then moment.utc().unix(). Although I am not sure it is't the right way. The server and MySQL server are both localhost, so the time is as it should be. – Liron Harel Mar 10 '15 at 06:43
  • I think that the problem is because the date that I stored in the server is already in UTC, hence the difference. – Liron Harel Mar 10 '15 at 06:51