如何将轮数转换为数据和时间格式

How to convert round number to data and time format

table tblpress 中的两列

Date          Time
20160307      120949
20160307      133427

需要select以下格式:

07-03-2016 12:09:49 07-03-2016 13:34 27

03-March-2016   12:09: 49 PM
03-March-2016   01:34: 27 PM

我认为CAST/CONVERT对你有帮助:

SELECT
  CAST('20160307' AS date),
  CAST(STUFF(STUFF('120949',3,0,':'),6,0,':') AS time)

并转换为:

SELECT
  CONVERT(varchar(20),NormalDate,105) OutDate, -- Italian style
  CONVERT(varchar(20),NormalTime,108) OutTime -- hh:mi:ss
FROM
  (
    SELECT
      CAST([Date] AS date) NormalDate,
      CAST(STUFF(STUFF([Time],3,0,':'),6,0,':') AS time) NormalTime
    FROM YourTable
  ) q

CAST and CONVERT (Transact-SQL)

你可以使用 FORMAT (Transact-SQL)

SELECT
  FORMAT(GETDATE(),'dd-MM-yyyy'),
  FORMAT(GETDATE(),'HH:mm:ss')

你可以试试下面

select format(cast([Date] as date),'dd-MMMM-yyyy') as [Date],
TIMEFROMPARTS(LEFT([Time],2), SUBSTRING([Time],3,2), RIGHT([Time],2), 0,0) as [Time]

最好的方法是创建一个函数:

create FUNCTION [dbo].[udfGetDateTimeFromInteger]
(
   @intDate int,
   @intTime int
)
RETURNS datetime
AS BEGIN
-- Declare the return variable here
DECLARE @DT_datetime datetime = NULL,
  @str_date varchar(11),
  @str_time varchar(8)
if(@intDate is not null and @intDate > 0)
begin
  select @str_date = CAST( cast(@intDate as varchar(8)) AS date)
  if @intTime=0
     select @str_time ='000000'
  else
     select @str_time = right('0'+CONVERT(varchar(11),@intTime),6)
  select @str_time = 
   SUBSTRING(@str_time,1,2)+':'+SUBSTRING(@str_time,3,2)+':'+SUBSTRING(@str_time,5,2)

  select @DT_datetime = CAST(@str_date+' '+@str_time as datetime)
 end
 -- Return the result of the function
 RETURN @DT_datetime

 END

然后在 select 中调用它,例如:

declare @next_run_date int, @next_run_time int
select @next_run_date = 20160307
select @next_run_time = 130949

SELECT  @next_run_date inputdate,
                @next_run_time inputtime,
                dbo.udfGetDateTimeFromInteger(@next_run_date, @next_run_time) outputdatetime

输出如下:

inputdate   inputtime   outputdatetime
20160307    130949      2016-03-07 13:09:49.000

你说那些是数字,对吧?您可以使用 datetimefromparts(或 datetime2fromparts)。即:

select 
 datetimefromparts(
  [date]/10000,
  [date]%10000/100,
  [date]%100,
  [time]/10000,
  [time]%10000/100,
  [time]%100,0)
from tblpress;

DB Fiddle demo

请注意,这样命名字段并存储日期和时间是个坏主意。

后来我注意到它是字符字段:

select 
  cast([date] as datetime) +
  cast(stuff(stuff([time],5,0,':'),3,0,':') as datetime)
from tblpress;