-1

Is it possible to exactly clone the DateTime value to Timespan data type. I converted the datetime to timespan by subtracting to min value. However, how do it display in DD MM YYYY HH MM SS format.

TimeSpan timeSpan = (DateTime)startTimeValue - DateTime.MinValue;
Darey
  • 497
  • 4
  • 24
  • Why do you care about the amount of time that's passed since midnight of the first of january 1 AD? What you have there is a date and time, not a time-span, so why not use the DateTime type for it? Especially if you're going to convert it to a string anyway. – Blorgbeard Jul 09 '15 at 03:43
  • Perhaps you want to convert startTimeValue itself to 'DD MM YYYY HH MM SS' format and for that use startTimeValue.toString("dd MM yyyy HH mm ss"). If not please explain your requirement to make it more clear. – ATP Jul 09 '15 at 03:45
  • I have to insert datetime value in db, but the datatype in db is provided as Timespan. I can't modify db type now so trying to manupulate through code. – Darey Jul 09 '15 at 03:53
  • What database is it? Are you sure it wants a .NET timespan and not the number of ticks or seconds since an epoch? – Stephen Kennedy Jul 09 '15 at 08:39

1 Answers1

0

Little bit late but since you didn't get any attention, so..

Is it possible to exactly clone the DateTime value to Timespan data type

Well, since your example works exactly since DateTime.MinValue has 0 as a Ticks. It is equivalent to;

TimeSpan timeSpan = TimeSpan.FromTicks(((DateTime)startTimeValue)Ticks);

how do it display in DD MM YYYY HH MM SS format

First of all, there is no DD, YYYY and SS as a custom date and time format specifiers. They are represented as dd, yyyy and ss.

TimeSpan is quite different than DateTime. It is a time interval but DateTime is a point in time. As you can see, a time interval can't have any month and year parts. In which Calendar? Not all calenders have 12 month. In which month exactly? How many months has 29 days are in GregorianCalender? Or ChineseLunisolarCalendar? It depends, right? Month and years concepts are ambigious for TimeSpan.

But still, you can format your TimeSpan as day, hour, minute and seconds with TimeSpan.ToString() method like;

timeSpan.ToString(@"d\.hh\:mm\:ss")

As a better alternative, you can use Nodatime which has Period class and PeriodUnits enum that you can calculate these like;

using System;
using NodaTime;

public class Program
{
    public static void Main()
    {
        LocalDate start = new LocalDate(2010, 11, 20);
        LocalDate end = new LocalDate(2015, 7, 13);

        Period period = Period.Between(start, end, 
                                       PeriodUnits.Months | PeriodUnits.Years);

        Console.WriteLine("{0} - {1}", period.Months, period.Years); // 7 - 4
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364