In C#, I want to make a function regarding DateTime trying to calculate relative time from scratch and what I made was this:
using System;
public class Program {
public static string getRelativeTime(DateTime past) {
DateTime now = DateTime.Today;
string rt = "";
int time;
if (past.Second >= now.Second) {
if (past.Second - now.Second == 1) {
rt = "second ago";
}
rt = "seconds ago";
time = past.Second - now.Second;
} // Then this process repeats until we hit years
string statement = time + "";
return statement + rt;
}
public static void Main() {
DateTime before = new DateTime(1995, 8, 24);
string date = getRelativeTime(before);
Console.WriteLine("Windows 95 was {0}.", date);
}
}
The problem about this though is that we can't return the value since it has been encapsulated by if statements, which I don't know how to fix. Of course break won't work since it is not a switch statement or a loop.
The expected output should be like this:
Windows 95 was 25 years ago.
So the main problem is, how to return an appropriate value in a function while the main values are actually being changed in if-statements?
Aucun commentaire:
Enregistrer un commentaire