3

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?

7
  • 2
    What value to do you expect to get as a result? Ticks, number of milliseconds, etc? Put a different way, how do you plan to use the result?
    – M.Babcock
    Feb 2, 2012 at 2:37
  • possible duplicate of How can I convert a DateTime value to a double? Feb 2, 2012 at 2:41
  • @M.Babcock, actually, 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 miliseconds as "091" how do you think?
    – Wenhao.SHE
    Feb 2, 2012 at 2:41
  • @Wenhao.SHE - You may want to add that detail to your question.
    – M.Babcock
    Feb 2, 2012 at 2:45
  • 1
    try and put all your info in your question, it tends to be annoying when people drip feed information. Feb 2, 2012 at 2:46

3 Answers 3

4
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

3
  • @Keith.Nicholas, String was not recognized as a valid DateTime. This is the complaint by running your code.
    – Wenhao.SHE
    Feb 2, 2012 at 3:11
  • sorry, should be HH not hh, changed my code, HH is for 24 hour time. Feb 2, 2012 at 3:17
  • actually, changed it to something better :) Feb 2, 2012 at 3:23
3

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.

0
0

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();

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.