Wenhao.SHE
Wenhao.SHE

Reputation: 2031

Convert date time with milliseconds to double or int?

I have a string looking good in the following way:

TimeString = "2011.01.02 22:06:52.091"

Now I wanna convert it to double, and save it as a double number. I am doing it in c#, how could I do it?

Really can not find answer online.

Edit:

The time is kind of time stamp for financial currency quote:

Time bid ask

2011.01.02 22:06:52.091 1.5000 1.5001

it is the time stamp of Forex quote time. I prefer in this way: xxxxxxxxxxxxxxxx.ooo, the xxxxxxxxxxxxxxx is the int part to show how many seconds we have from "2011.01.02 22:06:52" and the .ooo is the milliseconds as "091" how do you think?

Upvotes: 3

Views: 6164

Answers (3)

Keith Nicholas
Keith Nicholas

Reputation: 44316

var span = DateTime.ParseExact(TimeString,
                            "yyyy.MM.dd HH:mm:ss.fff",
                            CultureInfo.InvariantCulture) -
        new DateTime(2011, 01, 02, 22, 06, 52, 0);
double d = span.TotalMilliseconds/1000.0;

turns it into a double

Upvotes: 4

Cacho Santa
Cacho Santa

Reputation: 6924

I believe this is what you are trying to do:

static void Main(string[] args)
{
    String timeString = "2011.01.02 22:06:52.091";

    string format = "yyyy.MM.dd HH:mm:ss.fff";

    double date = DateTime.ParseExact(timeString, format, CultureInfo.InvariantCulture).ToOADate();

}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564851

There are a couple of options, but it's impossible to know what is "best" without knowing the use scenario.

If you can store this as a long (Int64), you can use DateTime.Ticks.

The other option is to use DateTime.ToOADate, which converts the DateTime to an OLE Automation date as a double.

To convert back, you can use the constructor that takes Ticks, or DateTime.FromOADate.

Upvotes: 3

Related Questions