Convert string date to system datetime in C# - asp.net

I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working...
DateTime ToDate = Convert.ToDateTime(txtToDate.Text);
DateTime FromDate = DateTime.Parse(txtFromDate.Text);
It shows the following exception
"String was not recognized as a valid DateTime."
How to do this...???

You could use DateTime.ParseExact(). That way you can specify the format of the input string, so it will be parsed correctly, for example:
dateString = "Sun 15 Jun 2008";
format = "ddd dd MMM yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}

whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format .
for different format you can check this :
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
for more help you can check similar question on this site :
Validate a DateTime in C#

You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit.
By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls.

Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss" or "dd/MM/yyyy hh:mm:ss tt" or "dd-MM-yyyy hh:mm:ss tt" or some other formats and use the help of following code to convert in to a Valid datetime.
DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>,
System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Instead, if the above coding makes complicated then you can try DateTime.TryParse() also

First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate.

DateTime dt = Convert.ToDateTime(date);
here date is in string.

Related

How to force RFC3339 string for all datetime for queries upon display as API?

Using Cake 3.2.4
What am I getting now?
Whenever a query is executed and there is a datetime field, it will be displayed as RFC2822 string.
e.g. "2016-07-18T09:00:00+0800"
What do I want?
I want RFC 3339 string
e.g. "2016-07-18T09:00:00+08:00"
What did I try?
$paginationQuery->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
$datetime = $row['start_date'];
$row['start_date'] = $datetime->format(\DateTime::RFC3339);
return $row;
});
});
I kinda forced the original datetime object to display as string.
Okay, so what's wrong?
I am unsure if it's wrong to do so. As you can see clearly, the original value for $row['start_date'] is actually a datetime object. Not a string.
Can I keep the value as datetime object but when it gets displayed as api, it uses the RFC3339 format?

DisplayFormat in MVC datetime [duplicate]

This question already has answers here:
Format datetime in asp.net mvc 4
(3 answers)
Closed 8 years ago.
I am trying to format date time attribute in MVC 4 class like this :
[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DateOfBirth { get; set; }
but not work DateOfBirth attribute accept date format month before day (EX:accept 1/27/1990 and not accept 27/1/1990)
I am searching for answers and trying many solution but not work like
enter link description here
using html helper:
#Html.TextBoxFor(Model => Model.DateOfBirth)
I appreciate any help thanks
The [[DisplayFormat] attribute is only for how to display the value in the view. It has nothing to do with the format that will be accepted. You can write some code to accept a string and in the server parse that back into a proper DateTime property. Store your DateTime, then when you go to display it back to the user you use your [[DisplayFormat] attribute
what you would do is use Regular Expressions to verify the user inputed a number then "/" then number then "/" then number.
Obivously you are not the first one to run into something like this , this is why datepickers are so commnly used , they force the user to pick a date and format it appropiatly
If your using #Html.TextBoxFor() to render the control, then [DataType(DataType.Date)] and ApplyFormatInEditMode = true in the [DisplayFormat] attribute is not really necessary. These are only applicable when you use #Html.EditorFor() to render the browsers date picker, in which case the format must be "yyyy-MM-dd" in order to display correctly in all browsers.
If you want to display the formatted date in a textbox, use
#Html.TextBoxFor(Model => Model.DateOfBirth, "{0:dd/MM/yyyy}")
Note if you post back "27/1/1990" (27th January 1990) and the current culture of the server has the date format "MM/dd/yyyy" then you will need a custom model binder to correctly bind the date. Refer example here

Converting any date format in MM/DD/YYYY format

I am having difficulty with different date formats. I am having a web application created using asp.net c#. I have used JQuery Calendar control which shows date along-with time.
I am then parsing this date using DateTime.Parse(). If the server is set with indian date format then the application generates conversion error "String was not recognized as a valid DateTime."
Is there a way to convert any date format into MM/DD/YYYY format along with time?
I know i can use DateTime.ParseExact() but again it will stuck with a particular format.
Any help is greatly appreciated.
Thanks for sharing you wisdom.
Convert.ToDateTime(DateTime.Now, CultureInfo.GetCultureInfo("en-US")).ToString("MM/dd/yyyy hh:MM:ss");
You can replace en-US by hi-IN for Hindi Date or as per you like. please follow link. for Culture Info.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx
If you are unsure of Culture then use below line.
Convert.ToDateTime(DateTime.Now, CultureInfo.CurrentCulture).ToString("MM/dd/yyyy hh:MM:ss");
reference here http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx
Other Method you can use is.
DateTime dt;
DateTime.TryParse(DateTime.Now.ToString(), out dt);
You can try DateTime.Parse or DateTime.TryParse methods
DateTime.Parse(DateTime.Now).ToString("MM/dd/yyyy hh:mm tt");
Also refer
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Thanks
Deepu
You can create an Extension methods for this you need to create a static class with static method. It will return you a date format that you define in class
public static class DateExtension
{
public static string GetDateTime(this DateTime? date)
{
if (date.HasValue)
return date.Value.ToString("dd-MMM-yyyy hh:mm tt");
return string.Empty;
}
}
Now in you code you can use this extension for e.g. DateTime.GetDateTime() it will return date with time that with the format you specify in your extension library class
string s;
s = dt.ToString("MM-dd-yyyy");
Console.WriteLine(s);//Displays 04-30-2012
You can use this code.
public static CultureInfo CreateCulture(string shortDateFormat)
{
CultureInfo newCulture = CultureInfo.CreateSpecificCulture("en-US");
newCulture.DateTimeFormat.ShortDatePattern = shortDateFormat;
newCulture.DateTimeFormat.LongDatePattern = shortDateFormat;
return newCulture;
}

showing DateTime in simple format?

i have a column in my database that stores DateTime, now i want to show time in simple format,
you know it will appear like : 12/26/2011 9:39:55 PM
but i want to show it in persian.
When you want to format the DateTime in your application, you need to use a DateTime.ToString overload.
Select the appropriate standard Date and Time format string - in this case "g" looks like a good fit.
If you have not set up your webserver to use the fa-IR culture by default, you will need to pass this culture in as well.
string farsiDate = myDateTime.ToString("g", CultureInfo.GetCultureInfo("fa-IR");
Have a look at the examples on MSDN for using the PersianCalendar class.
var cal = new PersianCalendar();
var today = DateTime.Now;
var persianDate = string.Format("{0}/{1}/{2}",
cal.GetDayOfMonth(today),
cal.GetMonth(today),
cal.GetYear(today));

date validation

can any one tell me the code to validate the date field in signup form(which shd also validate the leap year and no of days in each month
That depends on the input but suppose you have a string input for the whole date then you could try something like:
try
{
DateTime parsedDate = DateTime.Parse(incomingDateString);
}
catch
{
throw new Exception("Incoming Date string could not be parsed as a DateTime");
}
Alternatively if you have three integers as strings coming in from the form then you would replace the DateTime.Parse with
DateTime parsedDate = new DateTime(Int32.Parse(yearString), Int32.Parse(MonthString), Int32.Parse(DayString));
and allow the DateTime constructor take care of the details of analyzing days of month and leap years. You could be more sophisticated and use Int32.TryParse and provide more specific error messages and checks for null strings if thats what you need.
You can make sure you get a valid date by adding a calendar control or a date picker control. This will avoid having to add extra validation just to validate this field.
If you don't want to use a calendar control or date picker, you can use DateTime.Parse and place it inside a Try, Catch block.
dateString = YourDateField.Text;
try {
dateValue = DateTime.Parse(dateString);
}
catch (FormatException) {
Console.WriteLine("Unable to convert, this is not a valid date '{0}'.", dateString);
}
Hope this helps.

Resources