开发者

How to get DateTime formatted

开发者 https://www.devze.com 2023-02-08 07:29 出处:网络
In sql server how can I get current da开发者_JAVA技巧te but time 12:00 AM. With GETDATE() i get current date and time.I need to have datetime formated like this:

In sql server how can I get current da开发者_JAVA技巧te but time 12:00 AM. With GETDATE() i get current date and time.I need to have datetime formated like this:

2011-02-04 12:00 AM OR 2011-02-04 00:01


you first need to know how to get the time you want. It is called "flooring" date time. see this example:

--Floor a datetime

SELECT '0 None',  GETDATE()                                                                   -- none    2008-09-17 12:56:53.430
UNION SELECT '1 Second',DATEADD(second,DATEDIFF(second,'2000-01-01',GETDATE()),'2000-01-01')  -- Second: 2008-09-17 12:56:53.000
UNION SELECT '2 Minute',DATEADD(minute,DATEDIFF(minute,0,GETDATE()),0)                        -- Minute: 2008-09-17 12:56:00.000
UNION SELECT '3 Hour',  DATEADD(hour,DATEDIFF(hour,0,GETDATE()),0)                            -- Hour:   2008-09-17 12:00:00.000
UNION SELECT '4 Day',   DATEADD(day,DATEDIFF(day,0,GETDATE()),0)                              -- Day:    2008-09-17 00:00:00.000
UNION SELECT '5 Month', DATEADD(month,DATEDIFF(month,0,GETDATE()),0)                          -- Month:  2008-09-01 00:00:00.000
UNION SELECT '6 Year',  DATEADD(year,DATEDIFF(year,0,GETDATE()),0)                            -- Year:   2008-01-01 00:00:00.000
ORDER BY 1
PRINT' '
PRINT 'Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor'
PRINT 'this always uses a date less than the given date, so there will be no arithmetic overflow'
SELECT '1 Second',DATEADD(second,DATEDIFF(second,DATEADD(day,DATEDIFF(day,0,GETDATE()),0)-1,GETDATE()),DATEADD(day,DATEDIFF(day,0,GETDATE()),0)-1)  -- Second: 2008-09-17 12:56:53.000

once you floor it, use one of the flavors of CONVERT() to format it as you would like:

this does the format you want, but without changing the time:

select CONVERT(char(10), GETDATE(), 121)+' '+LTRIM(RIGHT(CONVERT(varchar(30), GETDATE(), 100),7))

OUTPUT:

------------------
2011-02-04 7:19AM

to format and set the time to what you want:

select CONVERT(char(10),DATEADD(day,DATEDIFF(day,0,GETDATE()),0), 121)+' '+LTRIM(RIGHT(CONVERT(varchar(30), DATEADD(day,DATEDIFF(day,0,GETDATE()),0), 100),7))

OUTPUT:

------------------
2011-02-04 12:00AM


Check out the CAST and CONVERT functions in T-SQL - they allow you to format your DATETIME values in various ways.


There are a number of Date functions you can use in SQL Server - See here.

Hopefully these will help!


To simply set the time to 12:00 AM but maintain the datetime datatype try:

SELECT DATEADD(DAY,0,DATEDIFF(DAY,0,GETDATE()))
0

精彩评论

暂无评论...
验证码 换一张
取 消