You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SELECT查询中将timestamp字段格式化为mm/dd/yyyy HH:MM:SS格式?

Fixing SSMA Timestamp Formatting Issues

Alright, let's break down what's going on here. First off, a critical clarification: in SQL Server, the timestamp type (now officially called rowversion) is a binary row version identifier—it doesn't store actual date or time data at all. That's exactly why your CAST(ssma_timestamp AS datetime) is returning wonky, unreadable results.

Since you mentioned this is an ssma_timestamp field, it's almost certainly a migration artifact from using the SQL Server Migration Assistant (SSMA) to bring data over from another database (like Sybase, MySQL, or Access). In those systems, timestamp often does represent a date/time value, which gets stored as binary data when migrated to SQL Server. Here's how to fix this:

Step 1: Convert Binary Timestamp to Datetime

Assuming your source database's timestamp stored milliseconds since the Unix epoch (1970-01-01 00:00:00), use DATEADD and CONVERT to turn the binary value into a proper datetime:

SELECT DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00') AS converted_datetime
FROM sa_project

Step 2: Format to mm/dd/yyyy HH:MM:SS

Once you have a valid datetime value, you can format it to your desired string format.

For SQL Server 2012 and later:

Use the FORMAT function for clean, readable formatting:

SELECT FORMAT(
    DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00'),
    'MM/dd/yyyy HH:mm:ss'
) AS formatted_datetime
FROM sa_project

For older SQL Server versions (pre-2012):

The FORMAT function isn't available, so use CONVERT with style codes instead:

SELECT 
    CONVERT(VARCHAR, DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00'), 101) 
    + ' ' + 
    CONVERT(VARCHAR, DATEADD(ms, CONVERT(BIGINT, ssma_timestamp), '1970-01-01 00:00:00'), 108) 
AS formatted_datetime
FROM sa_project

Here, style 101 gives you mm/dd/yyyy and style 108 gives HH:MM:SS—we just concatenate them to get your full desired format.

Important Notes:

  • If your source database used a different epoch (like 1900-01-01) or time unit (seconds instead of milliseconds), adjust the DATEADD parameter and base date accordingly.
  • If this really is a native SQL Server rowversion (timestamp) field, it can't be converted to a meaningful date/time—its only purpose is tracking row modifications. In that case, double-check your migration setup or look for another field that stores the actual timestamp of record changes.

内容的提问来源于stack exchange,提问作者goodk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:39:10