3

so I'm trying to display messages in a readOnly textbox, with the elapsed time and date, although I'm having some problems. It's displaying that the message was sent 325 days ago, when really it should be 1 min ago. Could someone please help to tell me what I've done wrong?

string[] date;
string[] messageArray = 
    File.ReadAllLines(Server.MapPath("~") + "/App_Data/messages.txt");

for (int i = 0; i < messageArray.Length; i++)
{
        date = messageArray[i].Split(' ');
        DateTime date1 = DateTime.Now;
        DateTime date2 = Convert.ToDateTime(messageArray[0]);
        TimeSpan timeDifference = date1.Subtract(date2);
        string formattedTime = "Sent " + timeDifference.Days + " days, " + 
         timeDifference.Hours + " hour/s," + 
         " and " + timeDifference.Minutes + " mins ago";

        File.AppendAllText(Server.MapPath("~") + 
              "/App_Data/messages.txt", "\n" + formattedTime + "\n");
        File.AppendAllText(Server.MapPath("~") + 
              "/App_Data/messages.txt", sendMessageTextBox.Text + 
              System.Environment.NewLine);

}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Kirstie Judd
  • 55
  • 2
  • 5

1 Answers1

8

Running the below

        DateTime date2 = DateTime.Now;
        Thread.Sleep(1000);
        DateTime date1 = DateTime.Now;

        TimeSpan timeDifference = date1.Subtract(date2);
        Console.WriteLine(timeDifference.Seconds);

Show output of 1

Print the value in messageArray[0] to see if it contain what you think it contains

Mzf
  • 5,210
  • 2
  • 24
  • 37
  • 6
    To express the net elapsed time in seconds, use timeDifference.TotalSeconds (total time expressed in seconds), rather than timeDifference.Seconds (which is the seconds component of the total time). – Guy May 15 '15 at 05:36