Convert the datetime into a string

Question : How to convert the datetime into a string for use in the SQL ' statement?

Answer :

Select a culture:


DateTime in Selected Culture





VB.NET

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

If Not Page.IsPostBack Then

Dim cInfo As CultureInfo

For Each cInfo In CultureInfo.GetCultures(CultureTypes.SpecificCultures)

ddlCulture.Items.Add(cInfo.Name)

Next

End If

End Sub


Private Sub ddlCulture_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCulture.SelectedIndexChanged

' Get a CultureInfo object based on culture selection in dropdownlist

Dim cInfo As CultureInfo = New CultureInfo(ddlCulture.SelectedItem.Text)

' Get a CultureInfo object based on Invariant culture

Dim cInfoNeutral As CultureInfo = New CultureInfo("")

' Display the datetime based on the formatting of the selected culture

TextBox1.Text = Convert.ToString(Now, cInfo.DateTimeFormat)

' Create a DateTime variable to hold the Invariant time

Dim dt As DateTime

dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat)

'Convert the datetime into a string for use in the SQL statement

Label1.Text = "... WHERE ([Date] < '" & _

Convert.ToString(dt, cInfoNeutral.DateTimeFormat) & "')"

End Sub

C#

private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

if (!Page.IsPostBack )

{

foreach(CultureInfo cInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))

{

ddlCulture.Items.Add(cInfo.Name);

}

}

}



private void ddlCulture_SelectedIndexChanged(object sender, System.EventArgs e)

{

// Get a CultureInfo object based on culture selection in dropdownlist

CultureInfo cInfo = new CultureInfo(ddlCulture.SelectedItem.Text);

// Get a CultureInfo object based on Invariant culture

CultureInfo cInfoNeutral = new CultureInfo("");

// Display the datetime based on the formatting of the selected culture

TextBox1.Text = Convert.ToString(DateTime.Now , cInfo.DateTimeFormat);

// Create a DateTime variable to hold the Invariant time

DateTime dt ;

dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat);

//Convert the datetime into a string for use in the SQL statement

Label1.Text = "... WHERE ([Date] < '" + Convert.ToString(dt, cInfoNeutral.DateTimeFormat) + "')";

}