Home > Enterprise >  How can I only display the date from MySQL database?
How can I only display the date from MySQL database?

Time:01-28

I only want to display the date from my database to a textbox which is a "yyyy/MM/dd" format. The problem is when I'm retrieving the data, it comes out as "28/01/2022 12:00:00 AM". How can I display just the date?

This is the output after retrieving the data.

CodePudding user response:

If you have a datetime field in SQL. You read into a vb.net variable

Dim myDateTime As DateTime = getDateTimeValueFromSQL()

or if you have a DateTime stored as a string in SQL (this is bad practice) you parse the string into a DateTime

Dim myDateTimeString As String = getDateTimeStringFromSQL()
Dim myDateTime As DateTime = DateTime.ParseExact(myDateTimeString, "dd/MM/yyyy hh:mm:ss tt", Globalization.CultureInfo.InvariantCulture)
' "dd/MM/YYYY hh:mm:ss tt" here according to format in SQL

then if you want to change how it is displayed as a string, you just use a string format method

TextBox1.Text = $"{myDateTime:yyyy/MM/dd}"
' or
TextBox1.Text = myDateTime.ToString("yyyy/MM/dd")
  •  Tags:  
  • Related