Convert YYYYMMDD string to MM/DD/YYYY string - c#

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:
txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);
However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.

DateTime.ParseExact with an example
string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));

Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);
Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
Then your code will work.

Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.

You want the method DateTime.ParseExact.
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);

Related

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

C# convert DateTime from one format to another

I thought this would be a really simple, and i've tried to google it and I keep getting the exception String was not recognized as a valid DateTime.
This is my value "2013-10-21T14:10:49" this is what I want to convert it into 10/21/2013 10:49
string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
When you write DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", ...), you are saying that sample is in the format MM/dd/yyyy HH:mm. Since it is not, it throws an exception.
It's important to know that a DateTime does not have any format associated with it. It's only when you convert it to or from a string that format can come into play. You should probably use something like this:
string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.Parse(sample, System.Globalization.CultureInfo.InvariantCulture);
string date31string = date31.ToString("MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
// date31string is "10/21/2013 14:10"
Instead of ParseExact, I used Parse, since the format is recognized by Parse, and I don't see much point in limiting what sort of formats it can accept to only that particular format.
Your string appears to be in format of "Xml-serialized". So it is the job of XmlConvert.
string sample = "2013-10-21T14:10:49";
string converted = XmlConvert.ToDateTime(sample, XmlDateTimeSerializationMode.Unspecified)
.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
You don't need the ParseExact method, the Parse method is sufficient because it allows your date representation. See DateTime - The string to parse for an overview of allowed input formats.
This means the following works:
string sample = "2013-10-21T14:10:49";
DateTime parsed = DateTime.Parse(sample);
Console.WriteLine(parsed.ToString("MM/dd/yyyy HH:mm:ss"));
And the result is:
10/21/2013 14:10:49

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

how to give format DateTime.Date?

DateTime dt = DateTime.Now
dt.Date is created to 31.10.2012 00:00:00 .it is created to dd.mm.yyyy format but i need dd/mm/yyyy. Can i use: return new DateTime(d.Year, d.Month, d.Day, 0, 0, 0); it will create to me dd/mm/yyyy solution?Please dont translate String.i need datetime...
The DateTime struct doesn't store any formatting information internally. If you want to output the DateTime instance as a formatted string, you just need to call ToString() with the proper format string:
var date = DateTime.Now;
var formattedString = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
If you need more information on exactly which specifiers to use in your format string, check out:
MSDN - Custom Date and Time Format Strings
Just the way to convert to string, DateTime itself has no format:
var result = DateTime.Now.Date
.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
var dt = DateTime.Now;
var stringDt = dt.Date.ToString("dd/MM/yyyy");
In you case you can simply use :
dt.ToString("dd/MM/yyyy");
Anyway there al the string format you can use with DateTime : Here.
System.DateTime does not have any format. You can view its string representation in format.
Try this
Console.WriteLine(DateTime.Now.Date.ToString("dd'/'MM'/'yyyy"));
DateTime, numeric types and most other types do not store their values in a formatted way. Rather they store their data using a binary representation. If you want to display this data to the user, you must convert it to a string. This conversion involves formatting the data.
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy",
CultureInfo.InvariantCulture);
Or
Console.WriteLine("Date = {0:dd/MM/yyyy}", DateTime.Now);
Console.WriteLine converts the date into a string in order to write it to the console.
DateTime structure always has the Date and Time stored in it. If you need to extract the date alone as text you can do the following.
var date = DateTime.Now.ToString("d");
Console.WriteLine(date);
This will print the date as in the format as specified by the culture set in the system. The list of standard datetime format strings supported by dotnet framework can be found here

String to datetime

I have a string 12012009 input by the user in ASP.NET MVC application. I wanted to convert this to a DateTime.
But if I do DateTime.TryParse("12012009", out outDateTime); it returns a false.
So I tried to convert 12012009 to 12/01/2009 and then do
DateTime.TryParse("12/01/2009", out outDateTime); which will work
But I don't find any straight forward method to convert string 12012009 to string "12/01/2009". Any ideas?
First, you need to decide if your input is in day-month-year or month-day-year format.
Then you can use DateTime.TryParseExact and explicitly specify the format of the input string:
DateTime.TryParseExact("12012009",
"ddMMyyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out convertedDate)
See also: Custom Date and Time Format Strings
You can use the DateTime.TryParseExact and pass in the exact format string:
DateTime dateValue = DateTime.Now;
if (DateTime.TryParseExact("12012009", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)))
{
// Date now in dateValue
}
If you want to use that format you will most likely need to specify the format to the parser. Check the System.IFormatProvider documentation as well as the System.DateTime documentation for methods that take an IFormatProvider.
DateTime yourDate =
DateTime.ParseExact(yourString, "ddMMyyyy", Culture.InvariantCulture);

Categories