DateTime Format - Getting System.FormatException in c# - c#

I am very new to C#.. I am writing an appointment schedule program where in I want to provide Date and Time value as a string from console and then I want to parse it to DateTime format. But by doing so I am getting
"System.FormatException" - string was not recognized as a valid datetime
Here is my piece of code,
string Format = "dd/MM/yyyy hh:mm tt";
Console.WriteLine("Enter the appointment date and time in(dd/MM/yyyy hh:mm AM/PM) format");
User_Input = Console.ReadLine();
Date_Time = DateTime.ParseExact(User_Input,Format,CultureInfo.InvariantCulture);
When I provide input exactly as format i.e like 23/11/2012 08:30 pm.. I am getting the said exception. I want to output datetime with AM/PM. What have I done wrong?

The question is a little bit odd since your format string works with your given input string(in all cultures) and you want to output with the same format. Perhaps somebody entered 23/11/2012 18:30 pm instead which does not work with the AM/PM designator.
string format = "dd/MM/yyyy hh:mm tt";
DateTime dateTime = DateTime.ParseExact("23/11/2012 08:30 pm", format, CultureInfo.InvariantCulture);
string output = dateTime.ToString(format, CultureInfo.InvariantCulture);
outputs: 23/11/2012 08:30 PM
demonstration
Note that you can always use DateTime.TryParseExact to validate user input.

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.

Remove time from my string c#

I am creating a web app in asp.net in which I am fetching the time from my database through string and printing the string date format in my database is 2016-10-15 00:00:00.000 and when I print the string the date format is showing like 10-Oct-16 12:00:00 AM but I just want to print 10-Oct-16 I tried
string reformattedDate = DateTime.ParseExact(txtdate, "dd-MM-yyyy", null)
.ToString("MMM d, yyyy");
This but it is me showing:
String was not recognized as a valid DateTime
Can anyone suggest me a better way?
Your date is yyyy-MM-dd hh:mm:ss.fff, the format you have inputted is only dd-MM-yyyy.
This is causing the error. Change this to:
string reformattedDate = DateTime.ParseExact("2016-10-15 00:00:00.000", "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture)
.ToShortDateString();
EDIT: You can also use ToString("dd-MMM-yy") instead of ToShortDateString() to get the desired output.
e.g.:
string reformattedDate = DateTime.ParseExact("2016-10-15 00:00:00.000", "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture)
.ToString("dd-MMM-yy");

How to convert a date string from "dd-MMM-yy" to "M/dd/yyyy hh:mm:ss tt"?

I need to compare two date format strings:
dateString in "dd-MMM-yy" format
with
referenceDateString in "M/dd/yyyy hh:mm:ss tt" format respectively.
For that, I need to convert the dateString = "dd-MMM-yy" to "M/dd/yyyy hh:mm:ss tt".
However, Got an error while trying to do that:
"Error: string was not recognized as a valid datetime".
The C# code I used given below.
string dateString = "19-Dec-14";
string AsofDate = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Edit 1:
In the actual code the dateString obtaining after reading a csv file which is supplied as "19-Dec-14", that's why it's in the string format.
Please help, am pretty new to C#. Thanks.
Habib already gave the answer on his comments, I try to add it as an answer;
From DateTime.ParseExact(String, String, IFormatProvider)
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
In your case, clearly they don't. First, you need to parse your string to DateTime with proper format (which is dd-MMM-yy with an english-based culture), then you can get the string represention of your DateTime with specific format.
string s = "19-Dec-14";
DateTime dt;
if(DateTime.TryParseExact(s, "dd-MMM-yy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).Dump();
// Result will be 12/19/2014 12:00:00 AM
}
It's not entirely clear what you are trying to do, but in order to parse that date you have on the first line, you would use something like this:
DateTime AsofDate = DateTime.ParseExact(dateString, "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
Note a couple things here: I've changed the data type of AsofDate from string to DateTime because that's what DateTime.ParseExact returns. Also, I've modified the custom format string to match the format of the string you are trying to parse as a date ("19-Dec-14").

Convert custom date to mysql datetime

I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.

Parsing a string to DateTime, formatting, then back to string - C#

I'm pulling a date/time from a MS SQL Server 2008 db and trying to format the date to show just the date in "dd/MM/yyyy" format.
The data in the DB looks like this:
2011-05-04 15:50:00.000
The unformatted string when displayed appears as this:
5/25/2011 8:47:00 AM
Yet this code fails when I try to parse it to the correct format:
DateTime dateA = DateTime.ParseExact(curShopDate, "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture);
curShopDate = dateA.ToString();
I also tried this code, trying to split just the date portion away from the time:
string[] stringA = curShopDate.Split(' ');
DateTime dateA = DateTime.ParseExact(stringA[0], "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture);
curShopDate = dateA.ToString();
Both versions crashed with an "String was not recognized as a valid DateTime." error.
The issue is with your format parameter. Your string is not in the ddMMyyyy format, it's in the M/dd/yyyy format:
string curShopDate = "5/25/2011 8:47:00 AM";
DateTime dateA = DateTime.ParseExact(curShopDate.Split(' ')[0], "M/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
You could also parse the string without stripping the time from the date:
string curShopDate = "5/25/2011 8:47:00 AM";
DateTime dateA = DateTime.ParseExact(curShopDate, "M/dd/yyyy h:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture);
According to MSDN:
The DateTime.ParseExact(String, String, IFormatProvider) method parses
the string representation of a date, which must be in the format
defined by the format parameter. It also requires that the and
elements of the string representation of a date and time appear
in the order specified by format, and that s have no white space other
than that permitted by format.
So, if I'm reading that correctly, you specified the format as "ddMMyyyy" but your string is in "M/dd/yyyy h:mm:ss tt". Try either changing your format to "M/dd/yyyy h:mm:ss tt" or switch to DateTime.TryParse().
If you use ParseExact, then you must specify the exact format: "M/d/yyyy h:mm:ss tt", which matches your date string "5/25/2011 8:47:00 AM".
You can take the date component of a date/time with:
DateTime dateTime = DateTime.Now;
DateTime dateOnly = dateTime.Date;

Categories