Datetime conversion in C# - using formats - c#

I need to convert a String to DateTime format, for this I just tried like
DateTime.ParseExact(DateOfBirth,"MM/dd/yyyy",CultureInfo.InvariantCulture);
it's working fine when I pass the value like 05/30/2012.
But if I try to pass the value as 5/30/2012 its showing error:
String was not recognized as a valid DateTime
To fix this I tried like
DateTime.ParseExact(String.Format("{0:MM/dd/yyyy}", DateOfBirth), "MM/dd/yyyy",
CultureInfo.InvariantCulture);
it's still not working. Here If I try String.Format("{0:MM/dd/yyyy}", DateOfBirth) for the value 5/30/2012 its showing the same format instead of 05/30/2012.
How can I fix this, can anyone help me here...
check this link
string to DateTime conversion in C#

Use M/d/yyyy instead of the format specifier you're using. Using only a single M matches months with leading zeros as well. This is also true for d.

assuming your DateOfBirth string is always separated by slashes, you could try something like this:
string[] dateParts = DateOfBirth.Split('/');
DateTime.ParseExact(string.Format("{0:00}", dateParts[0]) + "/" + string.Format("{0:00}", dateParts[1]) + "/" + string.Format("{0:0000}", dateParts[2]));
I think the issue is the format string can't be recognized since DateOfBirth is not a DateTime object. Thus, you enforce formatting by reformatting the string yourself

There is an overload which might be of your interest
DateTime.ParseExact(DateOfBirth,
new[] { "MM/dd/yyyy", "M/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
This should help you take care of single as well as two digit month part (since 5 is failing for you as the format is MM)

Since you have separators in your string (ie /), you can just do;
DateTime.ParseExact(DateOfBirth,"M/d/yyyy",CultureInfo.InvariantCulture);
That will parse either single or double digit days/months. When you use MM/dd/yyyy, you're requiring them both to be double digit numbers, and that's obviously not what you want in this case.

Try just "d" instead of "MM/dd/yyyy".
So, the statement should be:
var date = DateTime.ParseExact(DateOfBirth, "d", CultureInfo.InvariantCulture);
The documentation for this is here:
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Edit
Oops, I misread the documentation. It should be "M/d/yyyy".

In case you need to make it culture-independent..
var dateTimeFormat = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentUICulture.Name).DateTimeFormat;
dateTimeFormat.ShortDatePattern =
Regex.Replace(Regex.Replace(dateTimeFormat.ShortDatePattern, "[M]+", "MM"), "[d]+", "dd");
var newDate = date.HasValue ? date.Value.DateTime.ToString("d", dateTimeFormat) : null;

Related

Date time format in C#

I need "24/01/2012" but Why it always returns "24/1/2012"
when I am using this
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", (SessionHelper.SearchFilingStartDate.Value.Day.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Month.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Year.ToString()));
Just do with this :
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);
SessionHelper.SearchFilingStartDate.Value seems to be a DateTime value.
Then pass it directly without all that string conversions for day, months and year.
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",
(SessionHelper.SearchFilingStartDate.Value);
The format string "dd/MM/yyyy" contains enough information to allow the Format method to prepare the resulting string directly from your DateTime value
You don't need the String.Format statement. You can do it with the Date's ToString method:
txtFilingStartDate = SessionHelper.SearchFilingStartDate.ToString.Value("dd/MM/yyyy");
There's a lot more information on the MSDN page for Custom Date and Time Format Strings
You are passing a string and the format you specified for it is unrecognized. Assuming that this is a datetime you are passing, don't do all that conversion first:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", SessionHelper.SearchFilingStartDate.Value)
When you format a string using a date/time formatting ({0:dd/MM/yyyy}) themethod is expecting an instance of DateTime, you are passing it a string
You probably want simply:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);

converting a string to a DateTime format

I'm trying to parse 09/01/2015 00:00:00 to the format yyyy-MM-ddThh:mm:ssZ using following method:
DateTime.ParseExact("09/01/2015 00:00:00", "yyyy-MM-ddThh:mm:ssZ", (IFormatProvider)CultureInfo.InvariantCulture);
But I'm getting String was not recognized as a valid DateTime
Can anyone tell me why? I believe 09/01/2015 00:00:00 is a valid DateTime format?
From DateTime.ParseExact
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 are not.
I assume your 09 part is day numbers, you can use dd/MM/yyyy HH:mm:ss format instead.
var dt = DateTime.ParseExact("09/01/2015 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Since CultureInfo already implements IFormatProvider, you don't need to explicitly cast it.
I don't understand this. So it means I first have to correct my string
and secondly I can do a ParseExact(). I thought ParseExact could
handle the given string...
ParseExact is not a magical method that can parse any formatted string you suplied. It can handle only if your string and format perfectly matches based on culture settings you used.
Try this code:
var text = "09/01/2015 00:00:00";
var format = "dd/MM/yyyy HH:mm:ss";
var dt = DateTime.ParseExact(text, format, (IFormatProvider)CultureInfo.InvariantCulture);
You'll notice that the format must structurally match the text you're trying to parse exactly - hence the ParseExact name for the method.
The format does not match, you need to change 09/01/2015 into 2015-01-09 or theyyyy-MM-dd part into dd/MM/yyyy.
The ParseExact-method is no ultimate method that converts ANY dateformat into another one, it is simply to parse a given string into a datetime using the provided format. Thus if your inout does not match this format the method will throw that exception.
As a datetime is internally only a number there is no need to convert one format into another at all, so as long as you know your input-format you can build a date from it which has nothing to do with any formatting which you may need when you want to print that date to your output. In this case you WILL need a formatter.
As most people have stated the error is coming from the fact that the date in string format doesn't match the format you are saying it's in. You are saying that 09/01/2015 00:00:00 is in the format "yyyy-MM-ddThh:mm:ssZ", which it's not, hence the error. To rectify this you need to either alter the format the string is in, or more likely, change the format you are saying the date is in. So change "yyyy-MM-ddThh:mm:ssZ" to "dd/MM/yyyy HH:mm:ss".
In a more long term view how are you arriving at that date? Is it possible that the format may change (input but the user)? If so it might be better to try and avoid the error being thrown and handle it better with TryParseExact. To make use of this best I generally output a nullable DateTime and then check if it's null. If you don't do this then if the parse fails it will simply make the output datetime the minimum value.
Something like this should work:
public DateTime? StringToDate (string dateString, string dateFormat)
{
DateTime? dt;
DateTime.TryParseExact(dateString, dateFormat, null, System.Globalization.DateTimeStyles.None, out dt);
return dt;
}
Then you can use it like this:
DateTime? MyDateTime = StringToDate("09/01/2015 00:00:00", "dd/MM/yyyy HH:mm:ss");
if(MyDateTime != null)
{
//do something
}
Another simple way to do this...
var dt = Convert.ToDateTime(Convert.ToDateTime("09/01/2015 00:00:00").ToString("yyyy-MM-ddThh:mm:ssZ"))

Converting string to valid DateTime

I know there are allot of questions regarding this, but I've been trying all day to get this conversion to work and have had no luck when applying the answers to the same question posted here. Every time I try to Parse the string to a DateTime, I get a "String was not recognized as a valid DateTime" exception. If I use Convert.ToDateTime, I can get a Date back from my string, but I need the hh:ss as well.
Here is my simplified code that is ruining my day:
var test = "2015-05-08T05:00Z";
DateTime testTime = new DateTime();
//testTime = Convert.ToDateTime(test);
testTime = DateTime.ParseExact(test, "mm/DD/yyyy HH:ss",
System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(testTime);
Why is this string not recognized as a valid DateTime when trying to convert?
All help is appreciated
Try this...
var test = "2015-05-08T05:00Z";
DateTime testTime = new DateTime();
testTime = DateTime.Parse(test, null, System.Globalization.DateTimeStyles.RoundtripKind);
Console.WriteLine(testTime);
Console.ReadLine();
Or even with DateTime.ParseExact()
var test = "2015-05-08T05:00Z";
DateTime testTime = new DateTime();
testTime = DateTime.ParseExact(test, "yyyy-MM-ddTHH:ssZ", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
Console.WriteLine(testTime);
Console.ReadLine();
Results:
The format string you are using ("mm/DD/yyyy HH:ss") doesn't match your input in any way.
Have you looked at the DateTime.ParseExact documentation? You could try something like this:
testTime = DateTime.ParseExact(test, "yyyy-MM-ddTHH:ssZ",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal);
A couple of notes:
There is no point in setting testTime = new DateTime() if you are going to parse it on the next line. Just drop that line entirely and use var testTime = DateTime.ParseExact(...);
Are you sure that HH:ss is what you want? That seems like a very strange way to write a time. HH:mm or mm:ss would make more sense.
You should fix your expected pattern and take the time zone into account.
If your need a DateTime of DateTimeKind.Local:
var date = DateTime.ParseExact("2015-05-08T05:00Z", "yyyy-MM-dd'T'HH:mm'Z'",
CultureInfo.InvariantCulture);
If your need a DateTime of DateTimeKind.Utc:
var date = DateTime.ParseExact("2015-05-08T05:00Z", "yyyy-MM-dd'T'HH:mm'Z'",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal
| DateTimeStyles.AdjustToUniversal);
You are doing an exact parse, which means that the parse format string must match exactly with your date literal string. But your parse format string in ParseExact
uses / instead of - in the test literal string.
has a space instead of the T in the test literal string
does not match Z at the end of your test literal string.
Further it is not in yyyy-MM-dd order of your test literal string.
#Shar1er80' s solution is nice and frees you from having to specify a correct parse format string for ParseExact. I'd recommend going with that.
However, if you want to use ParseExact, you need to do this:
testTime = DateTime.ParseExact(test, "yyyy-MM-ddTHH:ssZ",
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
Note that I added a DateTimeStyle of AdjustToUniversal to ensure that your time is interpreted as UTC. The Z in the parse format string is just there to consume a Z. See https://stackoverflow.com/a/833143/49251 for more info on the issue of Z not actually being a part of the format string per se.

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

DateTime FormatException error

DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
txtDatumDokum.Text is like "09.09.2011".
but i get FormatException error. Must i parse date?
Try DateTime.ParseExact with the dd.MM.yyyy format string
DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
It's not good to see, anyway try this:
string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
s.Replace(".",
new System.Globalization.DateTimeFormatInfo().DateSeparator));
You need to tell us why the text input is using this format. If it is because the user enters it this way, then you need to make sure that the format matches that given by Thread.CurrentCulture.DateTimeFormat.ShortDatePattern. Changing the culture (by setting
Thread.CurrentCulture) to an appropriate value will then solve your problem.
If you are supposed to parse the input no matter what format it is in, then you will need to do some manual processing first (perhaps remove spaces and other delimiter characters from the input with string.Replace) and then try to parse the date using DateTime.ParseExact and a known format string.
But it all depends on why the input has that format, and why your application's current culture does not match it.
You could try this, TryParse avoids parsing exceptions.. Then you just need check result to be sure that it parsed.
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);
You will have to determine if this is a good solution for your application.
See this example:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Judging by the date you gave you need to include a culture, de-DE accepts 01.01.11 type of dates but I'm not sure which one you actually want to use, you'll need to decide that.. the Code would look like this:
using System.Globalization;
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);
A list of cultures can be found here, select the appropriate one for you:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
The plus here is that this code is a bit more work but it is very difficult to break. Assuming you are using a free text entry on a TextBox you don't want to be throwing exceptions.
Yes you have to parse input date in current culture.
string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;
if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
//Valid
else
//Invalid
DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)
It is right...there is no isssue
During a Deserialization call under compact framework 3.5 i've had some unexpected behaviour before.
I've converted from using the OpenNETCF serialization classes to the framework XML serialization class. In doing so, the default time format has changed and the order of property/public members. So long story short, i've exposed a text property which converts my date-times back to the format my VB6 application is expecting.
Dim dumbDate As New Date
Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
"yyyy-MM-dd HH:mm:ss:fffffffzzz"}
_datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
' There is something wrong with compact framework during the Serialization calls.
' calling the shared method Date.Parse or Date.ParseExact does not produce the same
' result as calling a share method on an instance of Date. WTF?!?!?!
' The below will cause a "Format" exception.
'_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
Date.blah doesn't work. dumbDate.blah works. strange.
public static void Main(string[] args)
{
var dt = new DateTime(2018, 04, 1);
Console.WriteLine(dt);
string month = dt.ToString("MMMM");
Console.WriteLine(month); //April
month = dt.ToString("MMM");
Console.WriteLine(month); //Apr
month = dt.ToString("MM");
Console.WriteLine(month); //04
Console.ReadKey();
}
your code:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
try changing this to:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);
and when u print the date/time
print datuMDokumenta.Text

Categories