ตัวออย่างการแปลง C# String to DateTime ใน .NET ภาษา C#
Tag : .NET, C#
Date :
2011-12-03 06:58:24
By :
agent
View :
4328
Reply :
7
No. 1
Guest
Code (C#)
// Date strings are interpreted according to the current culture.
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008"
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);
// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
// Alternate choice: If the string has been input by an end user, you might
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);
/* Output (assuming first culture is en-US and second is fr-FR):
Year: 2008, Month: 1, Day: 8
Year: 2008, Month: 8, Day 1
*/
Date :
2011-12-04 06:58:48
By :
....
No. 2
Guest
Code (C#)
usecarTableAdapter use = new usecarTableAdapter();
use.Insert(txtuseid.Text, txtidcars.Text,Convert.ToDateTime(txtusedate.Text.Trim()), txttimestart.Text="", txttimeend.Text="", Convert.ToDecimal(txtmitstart.Text), Convert.ToDecimal(txtmitend.Text), Convert.ToInt32(lbltotalmon.Text));
อยากทราบการ insert เวลา ที่ txtusedate.Text = DateTime.Now.ToShortDateString(); ที่อยู่ใน text box save เข้าไปในตาราง ไม่ทราบว่าข้างบนถูกไหม มีวิธีแก้
Quote:
Input string was not in a correct format.
Code
Line 179: use.Insert(txtuseid.Text, txtidcars.Text,Convert.ToDateTime(txtusedate.Text.Trim()), txttimestart.Text="", txttimeend.Text="", Convert.ToDecimal(txtmitstart.Text), Convert.ToDecimal(txtmitend.Text), Convert.ToInt32(lbltotalmon.Text));
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: Input string was not in a correct format.
Source Error:
Line 179:
Line 180: usecarTableAdapter use = new usecarTableAdapter();
Line 181: use.Insert(txtuseid.Text, txtidcars.Text, DateTime.Parse(txtusedate.Text, System.Globalization.CultureInfo.CurrentCulture), txttimestart.Text, txttimeend.Text, Convert.ToDecimal(txtmitstart.Text), Convert.ToDecimal(txtmitend.Text), Convert.ToInt32(lbltotalmon.Text));
Line 182:
Line 183:
จาก Convert.ToDateTime(txtusedate.Text.Trim())
เป็น "Convert(datetime, ' "+Convert.ToDateTime(txtusedate.Text.Trim())+" ',103)"
103 format ใน sql server
datetime คือ type ใน sql server