We often see in the comments how many days ago, how many hours ago.
The principle of implementation: now time-past time to get the difference between the comparison
Below I define a helper class, you can directly reference, parameter is the time difference, note that the time difference type is a timespan type, not a DateTime type OH ~
TimeHelper.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceTime Test {/// <summary> ///calculates the approximate time of a comment based on the past and present two datetime differences/// </summary> Public classTimehelper { Public Static stringGettimespan (TimeSpan ts) {if(Math.floor (TS. Totaldays) >365) { returnMath.floor (TS. Totaldays)/365+"years ago"; } Else if(Math.floor (TS. Totaldays) > -) { returnMath.floor (TS. Totaldays)/ -+"months ago"; } Else if(Math.floor (TS. Totaldays) >1) { returnMath.floor (TS. Totaldays) +"days ago"; } Else if(Math.floor (TS. TotalHours) >1) { returnMath.floor (TS. TotalHours) +"hours ago"; } Else if(Math.floor (TS. Totalminutes) >1) { returnMath.floor (TS. Totalminutes) +"minutes ago"; } Else { returnMath.floor (TS. TotalSeconds) +"seconds ago"; } } }}
Use C # to change the published time to a few years ago, a few months, a few days ago, a few hours ago, a few minutes ago, or a few seconds ago