C# with mongodb DateTime Convert - c#

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.

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.

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.

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

Related

How to convert to system datetime format from a string?

I need to convert a string datetime format to a DateTime field which should be in system Datetime format?
I've tried Convert.ToDateTime, DateTime.Parse, DateTime.ParseExact but all of them convert to dd-MM-yyyy HH:mm:ss format.
My string is in yyyy-MM-dd HH:mm format.
I was trying TryParseExact and specifying the culture also but I just couldn't understand that how it works. Below is the code that I am trying and my item.CreationDate is in "yyyy-MM-dd HH:mm" format
DateTime dateTime;
bool isSuccess1 = DateTime.TryParseExact(item.CreationDate, "yyyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTime);
DateTime result = dateTime;
Thanks in advance.
Can it be this easy? - yyyyy-MM-dd HH:mm has 5 ys in your example, not 4.
When you convert a string to DateTime you must state what format the input is in (as you have). If the conversion succeeded the DateTime object will hold the data for all the date parts (years, months, days etc.) and if you want to view them as a date again you must state what format you want to see them in. When using DateTime.TryParseExact it's worth noting that if the conversion fails it will set the value to the DateTime.MinValue.
There are various ways of showing the date again. The most common is stating the custom format for the date as a string. Another way is to use a standard format.
var creationDate = "2020-04-13 13:23";
DateTime.TryParseExact(creationDate, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateTime);
var myCulture = new CultureInfo("en-GB");
if(dateTime > DateTime.MinValue)
{
Console.WriteLine("Your custom format date is: " + dateTime.ToString("yyyy-MM-dd HH:mm"));
Console.WriteLine("Your standard format date is: " + dateTime.ToString("g", myCulture));
}
When you put this into a console app the results are like this:
With some of the standard format ones you will need to define the culture as it will be different for something like the en-US compared to something like zh-CN. In my case I used 'en-GB'. Here's a list of the accepted culture codes.

How to convert DateTime in dd/MM/yyyy to DateTime in dd-MM-yyyy?

I have gone through many questions and answers here regarding Datetime format conversion. Almost all are related to converting the format to output as a String.
Now I want to convert a DateTime variable in local format (dd/MM/yyy) to a DateTime variable in dd-MM-yyyy format for providing it as an input parameter for an API method.
I have tried several method like mentioning InvariantCulture while parsing and all. Even tried using Hebrew calendar for setting current culture also. Everything is returning the DateTime in local format(dd/MM/yyyy) itself and when providing that datetime variable to API is returning error message as to provide datetime in dd-MM-yyyy format only.
Is there any way to convert a datetime variable to a specific format?
Edit:
Is there is any way to convert datetime to a specific format? I am attaching some screen-shots below for reference.
I am using a third-party API, and I don't want to disclose the methods.
Method structure
Error response from the API method
Now I hope there is now way for specifying a format for DateTime variable.
First of all - DateTime has no some formats. string that represents DateTime can have formats.
To convert DateTime to specific format to string you can use ToString()
method:
DateTime dt = DateTime.Now;
string date = dt.ToString("dd-MM-yyyy");
To parse string to DateTime you can use ParseExact() method:
string date = "02/03/2017";
DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
or
string date = "02-03-2017";
DateTime dt = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
FOR YOUR EDIT:
Convert.ToDateTime() without CultureInfo tries to convert string to DateTime using your PC culture. If you want to use Convert.ToDateTime() use overloaded method that accept string and culture:
DateTime dt = Convert.ToDateTime(someDate, CultureInfo.InvariantCulture);
I use ToString Method and give pattren for parameter.
for example :
DateTime.Now.ToString("dd-MM-yyyy")

DateTime.TryParse cannot parse DateTime.MinValue

I'm using a library called Json.NET that uses the following code internally to parse a JSON string into a DateTime:
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt);
return dt;
}
I thought Json.NET was screwing up the conversion, but it looks like it's DateTime.TryParse itself that's botching the value.
When I parse the following valid Iso date (which corresponds to UTC DateTime.MinValue):
string json = "0001-01-01T00:00:00+00:00";
DateTime dt;
DateTime.TryParse(json, invariantCulture, DateTimeStyles.RoundtripKind, out dt);
The result is a localized DateTime: {0001-01-01 8:00:00 PM}, which when converted back to Utc time gives {0001-01-02 0:00:00 PM}. Essentially, the date underflowed, which is exactly the kind of problem you would expect DateTimeStyles.RoundtripKind to avoid.
How do I avoid this scenario?
Why use DateTimeStyles.RoundtripKind? The documentation for RoundtripKind says:
The DateTimeKind field of a date is preserved when a DateTime object is converted to a string using the "o" or "r" standard format specifier, and the string is then converted back to a DateTime object.
The string output from the "o" or "r" standard format specifiers are not like the ISO 8601 string you are trying to parse. It doesn't sound to me like RoundtripKind is really supposed to work with any date time string format. It sounds like the round trip is for the DateTime.Kind property when the string is in a particular format.
Since you know the format of the string you are trying to parse, then I would suggest using DateTime.TryParseExact.
I have had to support a couple different versions of the ISO 8601 string - either of these formats are valid date-time values in ISO 8601 (and there are even more options for dates, times and fractional seconds, but I didn't those):
0001-01-01T00:00:00+00:00
0001-01-01T00:00:00Z
Here's a method that will handle either of these formats:
private bool TryParseIso8601(string s, out DateTime result)
{
if (!string.IsNullOrEmpty(s))
{
string format = s.EndsWith("Z") ? "yyyy-MM-ddTHH:mm:ssZ" : "yyyy-MM-ddTHH:mm:sszzz";
return DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out result);
}
result = new DateTime(0L, DateTimeKind.Utc);
return false;
}

Convert a string to datetime format in asp .net

I have a date time string "12-24-2013 15:19:29" which is in "MM-dd-yyyy HH:mm:ss". I want to convert this string to datetime. But the format should not change.ie, it should be the same "MM-dd-yyyy HH:mm:ss" format.
When I used following method,
DateTime dt2 = DateTime.ParseExact(date31strin, "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
the format is changed to "dd-MM-yyyy HH:mm:ss". I have tried some other method also, but still getting this same format.
First, you should be parsing the string to a DateTime and then format it to the second format using ToString() method.
//Convert your string to a DateTime
DateTime dt2 = DateTime.ParseExact(date31strin,
"MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//If you want to change the format
string secondFormat = dt2.ToString("Second format string");
Note: Date is a Date and it does not have a format. If you need to convert the string to a DateTime, first line of code is enough
You are not changing the format.
You are parsing a string into a DateTime object which does not have a format.
When you decide to present the DateTime, you can format it any way you wish.
to parse String to DateTime use method DateTime.TryParse (http://msdn.microsoft.com/cs-cz/library/ch92fbc1%28v=vs.110%29.aspx) and then use DateTime formating (http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx) to output to aspx page
//frndzz if you are using j query and you don't convert date in(MM/dd/yyyy) to //(dd/MM/yyyy) then this code will help you
// i try it and i get the answer
string sd=txtmydate.Text //sd=04/27/2015 (MM-dd-yyyy) format
string [] sdate = sd.Split('-');
string fd = sdate[1];
fd=string.Concat(sdate[1],"-",sdate[0],"-",sdate[2]);
DateTime dt = Convert.ToDateTime(fd);
txtshow.Text = dt.ToString("dd/MM/yyyy");
//txtshow will show you date as 27-04-2015 (dd/MM/yyyy) format
thanks
How to convert string to DateTime:
string iDate = "Absent";
aEmployeeAttendence.Intime = DateTime.Parse(iDate);
//aEmployeeAttendence (object)
//Intime (field)

C# Datetime format conversion

I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind

Categories