How can I get a datetime from this string '01/25/1955'? - asp.net

I have the following code:
Dim dtDoM As Nullable(Of DateTime)
If (txtMarriageDate.Text.Trim = "") Then
dtDoM = Nothing
Else
dtDoM = DateTime.ParseExact(txtMarriageDate.Text.Trim + " 00:00:00", "dd/MM/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture)
'dtDoM = Convert.ToDateTime(txtMarriageDate.Text)
End If
On the commented out section I was getting FormatException 'String not recognized as datetime' and on the new code I'm getting "System.FormatException = {"The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar."}"
EDIT: Answered. Can't believe I overlooked that.

Your date (01/25/1955) is in MM/dd/yyyy format, you're using dd/MM/yyyy in your format string.
Try using this: "MM/dd/yyyy hh:mm:ss"

I think you have the wrong format string. You want "MM/dd/yyyy hh:mm:ss", judging by your examples.

You got day and month reversed. This will work:
dtDoM = DateTime.ParseExact(txtMarriageDate.Text.Trim + " 00:00:00", "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture)

Related

Getting valid Datetime such as Month/day/year format

my string is like this "21.05.2013 00:00:00"
but i want like this : "05/21/2013";
so i used format
String.Format("{0:M d yy}", myObject.StartAt.ToString());
but instead of this "05/21/2013" it produce this
"05.21.2013 00:00:00"
Edited area ----------
i tried below code but it still give wrong format it still give "05.20.2013" instead of "05/20/2013";
DateTime arrivalDate = DateTime.ParseExact(hotelSearchModel.StartAt.ToString(), "dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture);
DateTime departureDate = DateTime.ParseExact(hotelSearchModel.StartAt.ToString(), "dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture);
request.arrivalDate = arrivalDate.ToString("MM/dd/yyyy");
request.departureDate = departureDate.ToString("MM/dd/yyyy");
Is StartAt a string or a DateTime? If it's a string, you'll need to convert it to DateTime for the formatting to work. Also, you'll need to change your formatting pattern to MM/dd/yyyy to get 05/21/2013:
DateTime dt = DateTime.ParseExact(myObject.StartAt, "dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture);
string s = dt.ToString("MM/dd/yyyy");

How to convert date string to specific date format?

I get date string value(3/13/2013 12:00:00AM) from database and i need to convert like this format (yyyy-mm-dd). Please help me solve this.
string targetdate = "3/13/2013 12:00:00AM";(getting date value from DB)
DateTime lastdate = DateTime.ParseExact(targetdate, "yyyy-mm-dd",
System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
And I tried
Iformatprovider = null.
but i getting same error "String was not recognized as a valid DateTime"
I think the problem is with the date time
"3/13/2013 12:00:00AM"
It should not be 12:00:00AM.
It should be 12:00:00PM.
Example
string targetdate = "3/13/2013 11:59:59AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy HH:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
lastdate=lastdate.AddSeconds(1);
You will get
3/13/2013 12:00:00 AM
I would suggest you to cast it in the database end.
If you are using sql server then
Example
The following script uses the CONVERT() function to display different formats. We will use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
The result would look something like this:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243
First you need to convert your date string to DateTime type object using the format "M/d/yyyy HH:mm:sstt" later you can get the formatted string using "yyyy-MM-dd". (You used lower case m for month, it should be upper case M for month.
string targetdate = "3/13/2013 12:00:00AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy hh:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
string newFormat = lastdate.ToString("yyyy-MM-dd");
newFormat would contain "2013-03-13"
DateTime conversion is really easy in .Net if you know which datetime format you have and in which format you convert that.
Here is example for this.
String origionalDate = "12/20/2013"; // Format : MM/dd/yyyy
string origionalFormat = "MM/dd/yyyy";
string convertInToFormat="dd/MM/yyyy";
String convertedDate;
DateTime objDT;
if (DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
{
convertedDate = objDT.ToString(convertInToFormat);
Response.Write("<b>Origional DateTime Format ( " + origionalFormat + " ) : </b>" + origionalDate);
Response.Write("<br/>");
Response.Write("<b>Converted DateTime Format ( " + convertInToFormat + " ) : </b>" + convertedDate);
}
else
{
Response.Write("<b>Not able to parse datetime.</b>");
}
For more details on this visit this link. Click Here...

Convert date time format from dd/MM/yyyy to MM/dd/yyyy [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert dd-mm-yyyy into mm/dd/yyyyy in C#
I want to Convert Date time format from dd/MM/yyyy to MM/dd/yyyy in C#
Is there any suggestion how to do that?
Please try:
string oldstr = "03/12/2011";
string strDate = DateTime.ParseExact(oldstr, "dd/MM/yyyy",null).ToString("MM/dd/yyyy");
Console.WriteLine(strDate);
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat; //--MM/dd/yyyy
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat; //--dd/MM/yyyy
DateTime result = Convert.ToDateTime("07/21/2011", usDtfi); //or: ("21/07/2011", ukDtfi)
Then you have a DateTime Object (result) and do whatever you want like:
string str = result.ToString("yyyy-MM-dd HH:mm:ss");
Happy Coding :)
try this
string DateString = "22/04/2011";
DateTime date = new DateTime();
date = DateTime.ParseExact(DateString, "dd/MM/yyyy");
string NewDateString = date.ToString("MM/dd/yyyy");

Converting date to day of week

is there any ready to go solution within the microsoft framework, regarding conversion of date to day?
For example, i would like to convert this string 21/03/2010 (dd/mm/yyyy) to Sunday
Dim d = DateTime.Parse("21/03/2010").DayOfWeek()
This code will print Sunday on the console window
Dim dateToShow as DateTime = new DateTime(2010, 03,21)
Console.WriteLine(dateToShow.DayOfWeek.ToString)
This should print "Sunday".
string myDateTimeString = "21/03/2010";
DateTime dt = DateTime.ParseExact(
myDateTimeString, "dd/MM/yyyy",
new CultureInfo("en-Us", true)
, DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine(dt.DayOfWeek);
I would use DateTime.TryParse() just to validate the user input.
Dim input As String = "2010/12/23"
Dim dateTime As DateTime
If DateTime.TryParse(input, dateTime) Then
Console.WriteLine(dateTime.DayOfWeek)
Else
Console.WriteLine("Invalid")
End If

How to convert to datetime

I have a dropdownlist that displays time. For example 8:00AM or 8:30AM.
When I save this time to database, I want to save as todays date + time.
eg: 8:00AM as 03/30/2009 8:00:00:000. Can anybody give appropriate code to convert as shown above?
I tried
Convert.ToDateTime(ddlStartTime.SelectedItem.Text)
But there is an error stating "String was not recognized as a valid DateTime."
VB.NET answer for Portmans Solution. Too many chars for comment so included here.
Dim time As String() = Me.DropDownList1.SelectedValue.Split(New Char() {":", " "})
Dim hours As Integer = Integer.Parse(time(0))
Dim minutes As Integer = Integer.Parse(time(1))
Dim ampm As Integer = 12
If time(2).ToLower() = "am" Then
ampm = 0
End If
Dim dt As DateTime = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes)
Have a look at DateTime.TryParse and DateTime.Today. Using them should be enough to do what you want.
Untested Code.
DateTime dt;
if (DateTime.TryParse(Dropdown1.SelectedValue, out dt))
{
DateTime result = DateTime.Today.AddHours(dt.Hour).AddMinutes(dt.Minute);
}
Basically, you just need to parse the time string. It will be automatically resolved to the current date.
Dim strTime As String = "8.30am"
Dim parsedTime As DateTime
If DateTime.TryParseExact(strTime, "h.mmtt", New System.Globalization.DateTimeFormatInfo(), Globalization.DateTimeStyles.None, parsedTime) = True Then
'Parse was successful.
Else
'Handle the error.
End If
Store as the value for each drop down item the number of minutes from midnight that the time represents. Then:-
valueToStore = DateTime.Today + TimeSpan.FromMinutes(Int32.Parse(value))
By storing using the value attribute of a HTML option to store a simple representation of the value you eliminate the codes dependancy on the actual format used to simply display the set of values. If it decided that the representation of the times be changed to use different format the rest of the code will continue to work unmodified.
var time = this.DropDownList1.SelectedValue.Split(':', ' ');
var hours = Int32.Parse(time[0]);
var minutes = Int32.Parse(time[1]);
var ampm = (time[2] == "PM") ? 12 : 0;
var dt = DateTime.Today.AddHours(hours + ampm).AddMinutes(minutes);
Parse your DropDownList for Hours and Minutes, then add them to DateTime.Today.
Read the parts of the time so you have hours and minutes, then use the following code:
DateTime myDate = DateTime.Now.Date;
myDate = myDate.AddHours(hours);
myDate = myDate.AddMinutes(minutes);
Use ParseExact so that you can specify the format that you are using.
h = hours in 12-hour clock format
. = literal character
mm = minutes as two digits
tt = AM/PM designator
Dim time As DateTime = DateTime.ParseExact(dropdown.SelectedValue, "h.mmtt", CultureInfo.InvariantCulture)
The components of the DateTime value that you don't specify in the string (year, month, date, seconds, time zone, era) uses DateTime.Today as default, which is exactly what you want in this case.
This always seems to work for me. May not be the most elegant way, but I have not had any issues so far.
dTime = DateTime.Now;
string time = this.DropDownList1.SelectedValue;
DateTime FormattedDateTime = Convert.ToDateTime(dTime.Date.ToShortDateString() +
" " + time);

Resources