简体   繁体   中英

How to split string value using c# asp.net

I want to split this 2015-08-11 10:59:41.830 value which is in datetime datatype format and convert it to the following format using c# asp.net.

August 11, 45 minutes ago

The given datetime( ie-2015-08-11 10:59:41.830 ) will compare with the current datetime and display like the above format.Please help me to do this.

You will need to parse your date using DateTime.Parse(string s) and once you have that, you take the current date ( DateTime.Now ) and subtract from it the parsed date.

This should yield a TimeSpan struct. Assuming that both of the dates will refer to the same date, you can then construct your string by taking the pieces you need from the parsed date (Day and Month) and from the time span (Hours, minutes and seconds).

For your specific format you can try ParseExact() "yyyy-MM-dd HH:mm:ss.fff"

static void Main(string[] args)
{
    //Given that previous and and now is the same day
    DateTime previous = DateTime.ParseExact("2015-08-18 10:59:41.830", "yyyy-MM-dd HH:mm:ss.fff", 
        System.Globalization.CultureInfo.InvariantCulture);
    DateTime now = DateTime.Now;
    double value = now.Subtract(previous).TotalMinutes;

    Console.WriteLine(string.Format("{0:MMMM dd}, {1} minutes ago", now, (int)value));
    Console.ReadLine();
}

npinti already explained it, here the code part;

string s = "2015-08-18 10:59:41.830";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    var ts = dt - DateTime.Now;
    Console.WriteLine("{0}, {1} minutes ago", 
                        dt.ToString("MMMM dd", CultureInfo.InvariantCulture),
                        ts.Minutes);
}

I run this code 2015-08-18 09:50 in my local time and it's generate August 18, 9 minutes ago as a result.

Remember, Minutes property represents minute component of the TimeSpan object and it's range is from -59 to 59 . If you wanna get all minutes based on TimeSpan object value, you can use TotalMinutes property (or even as (int)ts.TotalMinutes ).

You need this

  var yourString = "2015-08-11 10:59:41.830";
  var oldDate = DateTime.ParseExact(yourString, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
  //The above two steps are only for if you have date in `string` type, but if you have date in `DateTime` format then skip these.
  var difference = DateTime.Now - oldDate; 
  //here old date is parsed from string or your date in `DateTime` format

  var result = string.Format("{0:MMMM dd}, {1} minutes ago", oldDate, difference.Minutes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM