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.

4
  • 1
    Have you made any attempt yourself to solve this? What specific problem are you facing? Commented Nov 13, 2014 at 16:48
  • 1
    Put the c# code in your question Commented Nov 13, 2014 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.. stackoverflow.com/questions/3556144/… Commented Nov 13, 2014 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. Commented Nov 13, 2014 at 17:01

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.