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

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.