2

I want to convert "ISODate(\"2014-11-13T18:43:33.868Z\")" to c# datetime ex 2014-11-13 18:43:33. Value "ISODate(\"2014-11-13T18:43:33.868Z\")" take from MongoDB collection.

Please Help.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
tremnb
  • 89
  • 1
  • 1
  • 5
  • 1
    Have you made any attempt yourself to solve this? What specific problem are you facing? – DGibbs Nov 13 '14 at 16:48
  • 1
    Put the c# code in your question – Disposer Nov 13 '14 at 16:51
  • that's not a C# datetime..looks more like a `TimeStamp` format please show your C# code that you are currently using also do a google search since there are many examples out there and this has already been asked on SO previously.. show more effort please.. http://stackoverflow.com/questions/3556144/how-to-create-a-net-datetime-from-iso-8601-format – MethodMan Nov 13 '14 at 16:54
  • The C# MongoDB driver will do this sort of conversion for you. If you post your code we can see what you might be doing wrong. – JohnnyHK Nov 13 '14 at 17:01

3 Answers3

5

You can set DateTime in C# to UTC

var createDate = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc)

or

dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc)

Then insert type DateTime into mongodb It worked in my case.

DateTime C#

Inser mongodb same datetime

Dale K
  • 25,246
  • 15
  • 42
  • 71
2

You can store your date as a BsonDateTime object when you pull it from the database, then convert it as follows:

DateTime dt = bdt.ToUniversalTime();

And you may find this question useful to learn more about how ToUniversalTime() works.

Community
  • 1
  • 1
Augustin Popa
  • 1,423
  • 1
  • 19
  • 22
1

If I understand clearly, just because it writes ISODate in your string, that doesn't make it ISO 8601 format. The "O" or "o" standard format specifier complies ISO 8601 format and which is "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for a DateTime. That doesn't match with your string format.

If your all strings has a stable format like this, you can use custom date and time formats with literal string delimiter like;

string s = "ISODate(\"2014-11-13T18:43:33.868Z\")";
string format = "'ISODate(\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\")'";
DateTime date;
if(DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out date))
{
    Console.WriteLine (date);
}

If you want to string representation of your DateTime with "2014-11-13 18:43:33" format, you can use DateTime.ToString() method like;

date.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364