Format exception String was not recognized as a valid DateTime - asp.net

objTour.tourStartDate =
Convert.ToDateTime(
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", null)
.ToString("MM/dd/yyyy"));
where txtTourStartDate.Text="16/08/2012".
I have searched and read all posts related to this.

In a custom date format string, / denotes the culture-specific date separator, not the literal character /. Thus, the result of your code depends on the user's (or the server's) localization settings.
To make your code independent of culture-specific settings, you have two options:
Explicitly specify a culture that uses a slash as the date separator, e.g.
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture)
or escape the character, e.g.
DateTime.ParseExact(txtTourStartDate.Text, #"dd\/MM\/yyyy", null)
(note the # and the \).
Both should yield the desired result.

This will be enough:
objTour.tourStartDate = DateTime.ParseExact(txtTourStartDate.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);

Your original code works, although you are doing lot of unnecessary conversions. (DateTime -> ToString -> ToDateTime), the real issue is InvariantCulture. Since you are passing null for CultureInfo try CultureInfo.InvariantCulture.
Your original code:
objTour.tourStartDate =
Convert.ToDateTime(
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy"));
A better one could be:
objTour.tourStartDate =
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)

Related

Issue in converting Timespan variable to 12 hour format

I have a nullable variable Start time
Timespan? st=e.StartTime;//Null-able variable;
I am trying to get time in AM/PM format but I am unable to get it.
DateTime date = Convert.ToDateTime(st.ToString());
String f = String.Format("{0:hh:mm:tt}", date);
Error is:
System.FormatException: String was not recognized as a valid DateTime.
If you were to output the results of st.ToString(), you will find that it doesn't contain any date information, only hours, minutes and seconds.
This isn't a valid format for a DateTime, which generally contain date and time information.
You don't need to convert your TimeSpan to a DateTime to format it, you can just use TimeSpan.ToString():
string f = st.Value.ToString(#"hh\:mm\:tt");
For reference: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Also, note the \ before the :, you must do this if you want to include literal strings in the output, as mentioned at the bottom of that documentation page.
Converting a timespan to a date is not possible, a timespan represents x amount of minutes/hours/whatever and you cannot get an exact date from that alone. If you have a date as a starting point, you can add a timespan and that will give you the new date.
st.ToString() will return "System.Nullable<Timespan>" because that is what a nullable type returns - it does not override the default Object.ToString implementation, so returns the type name.
If you want the string of the actual timespan, then you would need to do st.Value.ToString(), but you should be checking for null first (i.e. st.HasValue == true)
Edit: Also see #Sean's comment about how to output the Timespan without converting to a DateTime first.
Edit: Turns out I was slightly wrong - st.ToString() doesn't return the above. So see Sean's answer.
First convert Timespan to Datetime by adding TimeSpan to a base date of 00:00 hrs. Then on that dateTime derive the 12 hr format.
DateTime.Now.Date.Add(OpenTimeSpan).ToString(#"hh\:mm\:tt")
The Accepted Answer is wrong.
You cannot return AM/PM for a TimeSpan because it is only concerned with the length of Time,
not a Time of Day - hench the name, "TimeSpan".
Convert to a DateTime first before converting to a String:
string sTimeOfDay = new DateTime().Add(st).ToString("hh:mm tt");
Note: If your TimeSpan is nullable, then you will need to add Conditional Logic to Handle Nulls and pass in ts.Value instead of ts:
string sTimeOfDay = (st == null ? null : new DateTime().Add(st.value).ToString("hh:mm tt") );

How do I validate a string to be a date in the format dd-M-y, and not be a past date?

I have a date field and the format is "dd-M-y", example 01-Jan-2013. First I want to check the format which must be "dd-M-y" and secondly the date shouldn't be in the past but can be today and onward.
How would I do that? I would like to use regular expressions but I don't know what a suitable one would be.
You should use DateTime.TryParseExact rather than using Regex to validate your DateTime
string testDate = "01-Jan-2013";
DateTime temp;
if (DateTime.TryParseExact(testDate,
"dd-MMM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out temp) &&
(temp > DateTime.Today))
{
//Valid date and greater than today
}
else
{
//Invalid date or less than today
}
I think you should bind the user to fill the date in correct format instead of checking for it...
The Best solution in this case would be MaskEditExtender

Incorrect Date Format and date generates

I have variable of a type DateTime objApplicationSummaryInfo.AdmissionDate. I am trying to assign a value, such as
objApplicationSummaryInfo.AdmissionDate = DateTime.ParseExact(
TextBox3.Text.ToString(), "dd/mm/yyyy", null);
But when i am assigning a value like 27/09/2012to a textbox3, the variable objApplicationSummaryInfo.AdmissionDate takes a value 1/27/2012 12:00:09. The format as well as the date comes back incorrect.
What possible code am I missing and what can be an alternate solution. Thanks for assistance.
mm is minutes.
MM is months
Custom Date and Time Format Strings
Your code should be:
objApplicationSummaryInfo.AdmissionDate = DateTime.ParseExact(
TextBox3.Text.ToString(), "dd/MM/yyyy", null);
You will also need to set the culture:
CultureInfo provider = CultureInfo.InvariantCulture;
objApplicationSummaryInfo.AdmissionDate = DateTime.ParseExact(
TextBox3.Text.ToString(), "dd/MM/yyyy", culture);
Otherwise it will use the culture of the machine running the code.
"dd/mm/yyyy" should probably be "dd/MM/yyyy"
mm - is for minutes
MM - is for months
objApplicationSummaryInfo.AdmissionDate = DateTime.ParseExact(
TextBox3.Text.ToString(), "dd/MM/yyyy", null);
You can try with - dd/MM/yyyy
DateTime.ParseExact(TextBox3.Text.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
hey are you Testing on localHost try it on Server i will work on server but not on localhots

xml and condition by dateTime

XML
<CalendarFairs>
<CalendarFair>
<DateStart>2011-04-05T00:00:00</DateStart>
<DateEnd>2011-04-09T00:00:00</DateEnd>
<Title>aaaa</Title>
<IdExecutive>1</IdExecutive>
</CalendarFair>
<CalendarFair>
<DateStart>2011-04-16T00:00:00</DateStart>
<DateEnd>2011-04-19T00:00:00</DateEnd>
<Title>bbb</Title>
<IdExecutive>2</IdExecutive>
</CalendarFair>
<CalendarFairs>
Code
var elements = from element in doc.Descendants("CalendarFair")
where DateTime.Parse (element.Elements ("DateStart").ToString())==DateTime.Now
select new
{
dateStart = element.Element("DateStart").Value,
dateEnd=element.Element("DateEnd").Value,
title=element.Element("Title").Value,
idExcutive = element.Element("IdExecutive").Value ,
};
foreach (var item in elements)//send this error
{}
System.FormatException: The string was not recognized as a valid DateTime. There is a
unknown word starting at index 0.
why error?
Try to change it as follows:
var elements = from element in doc.Descendants("CalendarFair")
let start = element.Element("DateStart").Value
where DateTime.Parse (start)==DateTime.Now.Date
select new
{
dateStart = start,
dateEnd=element.Element("DateEnd").Value,
title=element.Element("Title").Value,
idExcutive = element.Element("IdExecutive").Value ,
};
EDIT: based on the XML you have posted the query above works pretty well. Try to test it with this input:
<CalendarFairs>
<CalendarFair>
<DateStart>2011-04-05T00:00:00</DateStart>
<DateEnd>2011-04-09T00:00:00</DateEnd>
<Title>aaaa</Title>
<IdExecutive>1</IdExecutive>
</CalendarFair>
<CalendarFair>
<DateStart>2011-03-20T00:00:00</DateStart>
<DateEnd>2011-04-19T00:00:00</DateEnd>
<Title>bbb</Title>
<IdExecutive>2</IdExecutive>
</CalendarFair>
</CalendarFairs>
Note that I have inserted today's start date. Actually I think the result was empty just because there weren't entries with actual date.
It sounds like one or more of your input <DateStart> strings is not in a valid DateTime format.
Can you post some sample input XML?
It may be that you need to provide the date format using ParseExact - http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

Convert string 10/29/2010 according to users culture

How can I convert the english date 10/29/2010 or any language date to user culture date format
I am using the following code
CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
cultureInfo.DateTimeFormat.
string lng = cultureInfo.TwoLetterISOLanguageName;
DateTime dateTime = DateTime.Parse("10/29/2010", cultureInfo);
but it throws error when I try to parse it.
Any Idea how can I resolve this issue
Thanx
Use ParseExact with English (or invariant) culture to convert the String into a datetime, then you can use ToString to output in in the user's date format.
// this is in "d" (= short date) format of the invariant culture
var englishDateString = "10/29/2010";
// convert it to a datetime
var date = DateTime.ParseExact(englishDateString, "d", CultureInfo.InvariantCulture);
// now you can output the date in the user's culture
var localizedDateString = date.ToString("d");
If you want to be explicit, you can add CultureInfo.CurrentCulture as a second parameter to ToString, but it's not required, since this is the default if no culture is specified.
Here's an example of parsing a US date:
DateTime.Parse("10/29/2010", new CultureInfo("en-US"));
i had the same pain when facing date conversion and i used a function (code below), you can modify it as you wish. try it or get ideas from it and let me know if it was useful
Imports Microsoft.VisualBasic Imports System.Globalization Public Class DatumKonvert1
Public Shared Function DK1(ByVal myDMstring As String) As Date
Dim source As String = myDMstring
Dim d As DateTime = DateTime.ParseExact(source, "d'/'M'/'yyyy", CultureInfo.InvariantCulture)
Dim resultMydate As String = d.ToString("M'/'d'/'yyyy")
Dim mdx = DateTime.ParseExact(resultMydate, "M'/'d'/'yyyy", CultureInfo.InvariantCulture)
Return mdx End Function End Class
Use this:
public static string ChangeDateToUserFormat(string dateValue, string dateCulture)
{
CultureInfo dateCultureInfo = CultureInfo.GetCultureInfoByIetfLanguageTag(dateCulture);
DateTime date = DateTime.Parse(dateValue, dateCultureInfo);
return date.ToString(CultureInfo.CurrentCulture);
}
For example:
string date = ChangeDateToUserFormat("10\29\2010", "en-US");
Use DateTime.ParseExact("10/29/2010", "MM/dd/yyyy", CultureInfo.InvariantCulture); instead of DateTime.Parse
Once you have a DateTime, it is no longer bound to a specific culture, but can be output however you want it. Usually, this is with one of the DateTime .ToString methods, or shortcuts like .ToShortDateString(), which uses the current thread's culture.
Edit: Note, it helps if I put the month and day ones in the correct spots. Whoops.

Resources