私はDatetime
から秒、分単位、時間、日、月などを返したいと思います。TimeSpan asp.netからの月と日を返します
私は多くの場合、私は与えられた日時について
編集
を次の値
でコードをテストしたコード
public static string ReturnCreatedSince(DateTime createdOn)
{
//Get current datetime
var today = DateTime.Now;
// Get days in current month
var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);
double seconds = 60;
double minutes = seconds * 60;
double hours = minutes * 60;
double days = hours * 24;
//double weeks = days * 7;
double months = days * daysInMonth;
double years = months * 12;
//Convert created datetime to seconds
var datetimeInSeconds = (today - createdOn).TotalSeconds;
var createdSince = string.Empty;
if (datetimeInSeconds <= seconds) //seconds between 1 to 60
{
return TimeSpan.FromSeconds(datetimeInSeconds).Seconds.ToString() + " sec";
}
else if (datetimeInSeconds <= minutes)// Minuites between 1 to 60
{
return TimeSpan.FromSeconds(datetimeInSeconds).Minutes.ToString() + " mins";
}
else if (datetimeInSeconds <= hours)// Hours between 1 to 24
{
return TimeSpan.FromSeconds(datetimeInSeconds).Hours.ToString() + " hrs";
}
else if (datetimeInSeconds <= days)// Days between 1 to 24
{
return TimeSpan.FromSeconds(datetimeInSeconds).Days.ToString() + " jrs";
}
else if (datetimeInSeconds <= months)// Months between 1 to 24
{
return (datetimeInSeconds/months).ToString() + " m";
}
else if (datetimeInSeconds <= years)// Years between 1 to 12
{
return (datetimeInSeconds/years).ToString() + " yrs";
}
else
{
return createdOn.ToShortDateString();
}
}
のこのスニペットを書きました秒が60未満の場合、値を返す必要があります秒です。 秒数が60以下で(60 * 60)秒未満の場合は、分単位で値を返します。
今この日付は"createdOn": "2017-10-16T14:41:16.557"
です1か月の代わりに41日。私は埋め込まれたメソッドを使用する方が簡単かもしれませんそれを
は、なぜそれが正しいではないでしょうか?あなたは手で計算をしようとしましたか?あなたはどんな結果を期待していますか? – Pac0
これは私には分かりません: 'double seconds = 60; double minutes = seconds * 60; ':したがって、変数' minutes'には3600が含まれています。それから私は数分ではないと思います(変数名はあなたのコードを読んでいる私のようなものを意味します)。次の変数については同じ注意が必要です。 – Pac0
どうしたの? 1か月の代わりに38日かかりますか?その後、あなたの 'if'条件は間違っています。 –