Parse String date to specific format - c#

This is a String date:
dob = reader.GetValue(7).ToString();` return like "12/2/2012"
But I want to convert (before passing it) to this format "2012212", I have tried
string newDate = dob.ToString("yyyMMdd")
But I got the following error:
The best overloaded method match for
'string.ToString(System.IFormatProvider)has some invalid arguments
any idea ?

Not Exact way of getting output but it will work.
string dob = "12/2/2012";
string[] d1 = dob.Split('/');
string s = d1[2] + d1[1] + d1[0];

You could use SqlDataReader.GetDateTime if underlying return type is DateTime
Then you just need..
reader.GetDateTime(7).ToString("yyyyMdd");
In case, if it is stored and received as a string then I would suggest converting to DateTime first and then look for specific format.
var date = DateTime.ParseExact(dob, "dd/M/yyyy",CultureInfo.InvariantCulture);
var formattedDate = date.ToString("yyyyMdd");

DateTime.ParseExact(reader.GetValue(7), "dd/M/dd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyyMMdd");

If you have a date in a String with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:
DateTime dt = DateTime.ParseExact(dob, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");

You can try below method to convert string to date.
IFormatProvider culture = new CultureInfo("en-US", true);
dob = DateTime.ParseExact(reader.GetValue(7).ToString(), "dd/MM/yyyy", culture).ToString("yyyyMMdd");
Thank you.

Related

How to convert a date in the form of a string with this format (yyyy-MM-dd HH:mm:ss) to a DateTime object of this format (dd-MM-yyyy HH:mm:ss)

I'm currently using C# and I want to convert a string like "2022-01-15 18:40:30" to a DateTime object with this format "15-01-2022 18:40:30". Below is what I've tried.
string stringDate = "2022-01-15 18:40:30";
string newStringDate = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy HH:mm:ss");
DateTime newDateFormat = DateTime.ParseExact(newStringDate, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
But the result i keep getting is "2022-01-15T18:40:30"
Any help would be appreciated
As others pointed out, you have a internal data value for DateTime.
So, FOR SURE we suggest that you convert the string into that internal format.
Once you do that, then you are free to output that internal date time value to ANY kind of format and output you want.
Thus, we have this:
string stringDate = "2022-01-15 18:40:30";
DateTime MyDate = DateTime.ParseExact(stringDate,"yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);
// now we can output convert to anything we want.
Debug.Print("Day of week = " + MyDate.ToString("dddd"));
Debug.Print("Month = " + MyDate.ToString("MM"));
Debug.Print("Month (as text) = " + MyDate.ToString("MMMM"));
// desired format
Debug.Print(MyDate.ToString("dd-MM-yyyy HH:mm:ss"));
And output is this:
DateTime date = Convert.ToDateTime("2022-01-15");
DateTime time = Convert.ToDateTime("18:40:30");
DateTime dt = Convert.ToDateTime(date.ToShortDateString() + " " + time.ToShortTimeString());
try this style
Try this one:
string stringDate = "2022-01-15 18:40:30";
Console.WriteLine((DateTime.Parse(stringDate)).ToString("dd-MM-yyyy HH:mm:ss"));
The DateTime object by itself does not have a specific "format".
The string representation gets created when you call the .ToString() function.
There are multiple overloads of the ToString function with which you can specify the format.

getting issue with conversion from string to DateTime

I am getting issue while converting string to DateTime.
The value I am receiving as "08-26-2015 10:14:57.898Z".
I am trying to convert the above string to DateTime.
My Code:
DateTime.ParseExact(element.Value,"MM/dd/yyyy HH:mm:ss",CultureInfo.CurrentCulture);
Exception:
String was not recognized as a valid DateTime.
You have string with different format than you trying for conversion.
Try this
var input = "08-26-2015 10:14:57.898Z";
var date = DateTime.ParseExact(input, "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
You can use:
DateTime dt = DateTime.ParseExact("08-26-2015 10:14:57.898Z", "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
If you use CultureInfo.CurrentCulture(or null) the slash / has a special meaning. It is replaced with the current culture's date separator. Since that is not - but / in US you get an exception. Read
Have you tried Convert.ToDateTime ?
I just tried with your string and it works fine :
var s = "08-26-2015 10:14:57.898Z";
var date = Convert.ToDateTime(s);
String s = "08-26-2015 10:14:57.898Z";
DateTime date;
DateTime.TryParse (s, out date);
Now date variable contains DateTime value you need.

Converting a date string in C#

I have a date string with the format "dd.MM.yyyy" (eg. "01.02.2004") and want to convert it to "yyyy-MM-dd" with String.Format(...) or DateTime.ParseExact(...) or whatelse.
Actually I only get exceptions. So the usage of the following code doesn't work:
String dateString = "01.02.2004";
datestring = String.Format("{yyyy-MM-dd}", dateString);
What is wrong with that? Is there an alternative with DateTime.ParseExact(..)?
You need to parse it into a DateTime, then call ToString() with a different format:
DateTime date = DateTime.ParseExact(dateString, "dd.MM.yyyy", CultureInfo.InvariantCulture);
date.ToString("yyyy-MM-dd")
You need to create a Datetime object first.
try something like:
DateTime t = DateTime.parse("01.02.2004");
String result = t.ToString("{yyyy-MM-dd}", CultureInfo.InvariantCulture);
You have to convert it to a DateTime first with an appropriate CultureInfo:
String dateString = "01.02.2004";
var deCulture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE");
DateTime dt = DateTime.Parse(dateString, deCulture);
dateString = dt.ToString("yyyy-MM-dd");
Demo
String dateString = "01.02.2004";
dateString = DateTime.ParseExact(dateString, "dd.MM.yyyy", CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
What's wrong with your attempt is:
When using a format string, the items need to be listed in a format like {0:yyyy-MM-dd}. The 0: is necessary.
When you're using string.Format(), the variable is a string, so the format string yyyy-MM-dd has no meaning there.
You're parsing a string as argument to String.Format? What do you expect out of it?
You should do something like this:
try
{
var date = DateTme.ParseExact("yyyy.MM.dd", dateString, CultureInfo.InvariantCulture);
var result = date.ToString("yyyy-MM-dd");
}
catch(Exception e) { /* ... */}

DateTime.Parse with a custom DateTimeFormatInfo throws an exception

Why is this code throwing an exception?
var dateTime = "2012-03-21_15.12";
var format = new DateTimeFormatInfo()
{
FullDateTimePattern = "yyyy-MM-dd-HH_mm.ss"
};
// FormatException: String was not recognized as a valid DateTime.
var parse = DateTime.Parse(dateTime, format);
Your format string and the date string do not match.
You seem to have forgotten either the hours or minutes portion in the date string.
This:
var dateTime = "2012-03-21_15.12";
Should probably look like:
var dateTime = "2012-03-21-15_54.12";
And I suggest using DateTime.ParseExact:
DateTime.ParseExact("2012-03-21-16_15.12",
"yyyy-MM-dd-HH_mm.ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None)
You may want to use DateTime.ParseExact as this will take a datetime format pattern as a parameter.
DateTime.ParseExact

How to convert date format to DD-MM-YYYY in C#

How to convert date format to DD-MM-YYYY in C#? I am only looking for DD-MM-YYYY format not anything else.
string formatted = date.ToString("dd-MM-yyyy");
will do it.
Here is a good reference for different formats.
According to one of the first Google search hits:
http://www.csharp-examples.net/string-format-datetime/
// Where 'dt' is the DateTime object...
String.Format("{0:dd-MM-yyyy}", dt);
Here is the Simplest Method.
This is the String value: "5/13/2012"
DateTime _date;
string day = "";
_date = DateTime.Parse("5/13/2012");
day = _date.ToString("dd-MMM-yyyy");
It will output as: 13-May-2012
string formattedDate = yourDate.ToString("dd-MM-yyyy");
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
DateTime s1 = System.Convert.ToDateTime(textbox.Trim());
DateTime date = (s1);
String frmdt = date.ToString("dd-MM-yyyy");
will work
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
First convert your string into DateTime variable:
DateTime date = DateTime.Parse(your variable);
Then convert this variable back to string in correct format:
String dateInString = date.ToString("dd-MM-yyyy");
Here we go:
DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "-" + time.Month + "-" + time.Year);
WORKS! :)
From C# 6.0 onwards (Visual Studio 2015 and newer), you can simply use an interpolated string with formatting:
var date = new DateTime(2017, 8, 3);
var formattedDate = $"{date:dd-MM-yyyy}";
Do you have your date variable stored as a String or a Date type?
In which case you will need to do something like
DateTime myDate = null;
DateTime.TryParse(myString,myDate);
or
Convert.ToDateTime(myString);
You can then call ToString("dd-MM-yyyy") on your date variable
I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.
using System.Threading;
string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);
All you have to do is change the culture name, for example:
"en-US" = United States
"fr-FR" = French-speaking France
"fr-CA" = French-speaking Canada
etc...
The problem is that you're trying to convert a string, so first you should cast your variable to date and after that apply something like
string date = variableConvertedToDate.ToString("dd-MM-yyyy")
or
string date = variableConvertedToDate.ToShortDateString() in this case result is dd/MM/yyyy.
dateString = "not a date";
// Exception: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
DateTime dateTime11; // 1/1/0001 12:00:00 AM
bool isSuccess2 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime11);
var dateTimeString = "21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30";
dateTimeString = Regex.Replace(dateTimeString, #"[^\u0000-\u007F]", string.Empty);
var inputFormat = "dd-MM-yyyy HH:mm:ss";
var outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
var output = dateTime.ToString(outputFormat);
Console.WriteLine(output);
Try this, it works for me.
you could do like this:
return inObj == DBNull.Value ? "" : (Convert.ToDateTime(inObj)).ToString("MM/dd/yyyy").ToString();

Categories