226

I'm a MySQL guy working on a SQL Server project, trying to get a datetime field to show the current time. In MySQL I'd use NOW() but it isn't accepting that.

INSERT INTO timelog (datetime_filed) VALUES (NOW())
DMK
  • 2,448
  • 1
  • 24
  • 35
Andrew G. Johnson
  • 26,603
  • 30
  • 91
  • 135

5 Answers5

250

getdate() or getutcdate().

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Daniel Schaffer
  • 56,753
  • 31
  • 116
  • 165
88
getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

Steven A. Lowe
  • 60,273
  • 18
  • 132
  • 202
  • Are there any places where the time zone change straddles a date change? Here in PST, the time zone change always happens several hours past midnight. – Rei Miyasaka Jan 09 '21 at 00:34
33

SYSDATETIME() and SYSUTCDATETIME()

are the DateTime2 equivalents of

GetDate() and GetUTCDate()

which return a DateTime.

DateTime2 is now the preferred method for storing the date and time in SQL Server 2008+. See the following StackOverflow Post.

Community
  • 1
  • 1
DMK
  • 2,448
  • 1
  • 24
  • 35
29

You can also use CURRENT_TIMESTAMP, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate() under the covers (see this question for more on that).

There's no ANSI equivalent for GetUTCDate(), however, which is probably the one you should be using if your app operates in more than a single time zone ...

Community
  • 1
  • 1
Ian Varley
  • 9,227
  • 5
  • 29
  • 34
  • 5
    I like `CURRENT_TIMESTAMP` because it works in MySQL, SQL Server, Oracle... As you said, it's the least of our worries but it always helps. – Álvaro González Apr 09 '12 at 08:00
0

Following are the functions that you can use in SQL Server instead of NOW()

1. SYSDATETIME() 2. GETDATE () 3. GETUTCDATE() 4. CURRENT_TIMESTAMP

These functions give almost the exact Date and Time while SYSDATETIME gives a more precise time in milliseconds.

Query: SELECT SYSDATETIME()

Output: 2022-12-21 19:38:49.4181976

Query: SELECT GETDATE () | GETUTCDATE() | CURRENT_TIMESTAMP

Output: 2022-12-21 19:38:49.413