How to convert data/time to string in query?

F

Frank Xia

How to convert date/time to string in query? So I can handle it with using
"Left" or "Right" function.

Thanks for any help in advance!
 
B

Brendan Reynolds

You can do that with the Format function. However, if your purpose is to
extract a part of the date, you can do that in a more locale-independent way
using the various functions designed for that purpose, such as Year(),
Month(), Day(), etc.

Here's an example that on my system (where short date format includes
four-digit years) returns the same value in both columns (albeit one is a
string and the other is an integer). The first column might return a
different result on another system, the second column would not ...

SELECT Right$(Format$([OrderDate],"Short Date"),4) AS StringDate,
Year([OrderDate]) AS OrderYear
FROM dbo_Orders;
 
F

Frank Xia

Thanks for your help. That is what I need.

Brendan Reynolds said:
You can do that with the Format function. However, if your purpose is to
extract a part of the date, you can do that in a more locale-independent way
using the various functions designed for that purpose, such as Year(),
Month(), Day(), etc.

Here's an example that on my system (where short date format includes
four-digit years) returns the same value in both columns (albeit one is a
string and the other is an integer). The first column might return a
different result on another system, the second column would not ...

SELECT Right$(Format$([OrderDate],"Short Date"),4) AS StringDate,
Year([OrderDate]) AS OrderYear
FROM dbo_Orders;

--
Brendan Reynolds (MVP)

Frank Xia said:
How to convert date/time to string in query? So I can handle it with using
"Left" or "Right" function.

Thanks for any help in advance!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top