Remove time from my string c# - 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");

Related

How can I convert this date "03/01/2018 12:00 AM" to "2018-03-01" in C#?

I am using this code to convert a date 03/01/2018 12:00 AM to 2018-03-01 in C#:
DateTime startDate = DateTime.ParseExact(TextBox1.Text.ToString(),
"yyyy-mm-dd",
System.Globalization.CultureInfo.InvariantCulture);
but it throws an exception
String was not recognized as valid datetime
This Will Work Like A Charm
string bs = "03/01/2018 12:00 AM";
String startDate = DateTime.ParseExact(bs,"MM/dd/yyyy hh:mm tt",System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Console.WriteLine(startDate);
// Outputs 2018-03-01
You can verify the code here
A DateTime represents a particular point in time. ParseExact is a way of turning a string into a DateTime. By saying ParseExact with "yyyy-mm-dd" you are telling it that the string you are giving it begins with a four digit year, which it doesn't. Fix the format string that you are supplying so that the parse works.
Once you have the value in your DateTime variable, you can use ToString("yyyy-mm-dd") to turn that DateTime back into a string.
Remove AM from your Textbox and edit format string, then your sample code will work.
This line run successfully :
DateTime startDate = DateTime.ParseExact("03/01/2018 12:00", "MM/dd/yyyy hh:mm", System.Globalization.CultureInfo.InvariantCulture);
string inputDate = "03/01/2018 12:00 AM";
string outputDate = DateTime.Parse(inputDate).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

DateTime Format - Getting System.FormatException in 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.

For valid DateTime(Error shows string was not recognized )

I am trying to convert my string formated value to date type with format dd/MM/yyyy. It runs fine but when I enter fromdate(dd/MM/yyyy) in textbox its fine and todate(dd/MM/yyyy) in textbox then it gives an error that string was not recognized as a valid datetime.What is the problem exactly i dont know. same code run on another appliction its run fine but in my application it shows Error.
Below I have used array for required format and split also used.
string fromdate = punchin.ToString();
string[] arrfromdate = fromdate.Split('/');
fromdate = arrfromdate[1].ToString() + "/" + arrfromdate[0].ToString() + "/" + arrfromdate[2].ToString();
DateTime d1 = DateTime.Parse(fromdate.ToString());
try with DateTime.TryParseExact as below
DateTime date;
if (DateTime.TryParseExact(inputText, "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
if you know the format of input date time you don't need to do any string manipulation.
But you need to give correct Date and Time Format String
I got 5/13/2013 12:21:35 PM in string fromdate
Use DateTime.TryParseExact, You don't have to split your string based on / and then get first three items from the array instead you can simply do:
DateTime dt;
if (DateTime.TryParseExact("5/13/2013 12:21:35 PM",
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//date is fine
}
Using single d and single M as it can accomodate single digit as well as double digits day/Month part. You can simply pass punchin as the string parameter, Calling ToString on string types is redundant.
Try :
DateTime.ParseExact(fromdate, "MM/dd/yy", CultureInfo.InvariantCulture)
Obviously you can reformat the above, and use different providers by creating an instance of CultureInfo related to the string you are parsing, and you can modify the format string to reflect that culture or to accommodate more date parts

System DateTime Format is changed

I have Window 7 installed in my computer. The problem is that the system date format is changed some time if computer is restarted. I need to make the date format fixed but don't know how. I have application built in mvc 3 and have code for string to datetime conversion. If system datetime format doesn't match with string it show error that
string is not in proper format for converting into datetime which looks for system datetime. The exception is thrown in following code:
DateTime startDate = Convert.ToDateTime(start);
where,
string start = sundayOfLastWeek.ToString("MM/dd/yyyy HH:mm:ss");
Or, Is there any alternatives so that I can change in code that works all the time despite the system Date Time.
Use DateTime.ParseExact with the format "MM/dd/yyyy HH:mm:ss"
startDate = DateTime.ParseExact(start,
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
EDIT: based on comment from #John Woo
You can pass string array to DateTime.Parse like:
string[] dateFormats = new string[] { "MM/dd/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "d/MM/yyyy" };
DateTime startDate = DateTime.ParseExact(start,
dateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
use .ToString(CultureInfo.InvariantCulture) and Parse(value, CultureInfo.InvariantCulture) for values persistance. Only omit CultureInfo if you render values for display purpose. For some specific data formats special formatting rules may exist - follow them.
to recover your data use ParseExact.
As Habib already answered:
//Add any format you want or expect
string[] formats = { "MM/dd/yyyy HH:mm:ss", "dd.MM.yyyy HH:mm:ss" };
DateTime startDate = DateTime.ParseExact(start, formats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
It should help.

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