简体   繁体   中英

ways to format my date with 24hr

Could someone please show me a way in SQL and C# to format my date string like the following?

2/24/2012 22:00

Note: I don't need the seconds.

given:

declare @myDate varchar(50)
set @myDate = '2/24/2012 10:00 PM'

select @myDate

I'm showing the code snippet above to indicate that the date's source type is varchar.

In C# you can pass parameters to the ToString() method to get exactly what you want. It's well documented here: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

According to that you should try:

myDate.ToString("MM/dd/yyyy HH:mm");

In SQL Server <= 2008 R2, you can say:

SELECT  CONVERT(CHAR(10), CONVERT(DATETIME, @myDate), 101) 
+ ' ' + CONVERT(CHAR(5),  CONVERT(DATETIME, @myDate), 8)

However this will yield leading zeros that you don't seem to want (and that nobody else seemed to catch). If you want to keep your m/d/yyyy format (which isn't advisable anyway - better to use a language- and region-ambiguous format like yyyy-mm-dd), you might be best off just keeping that portion of the string as is, and just converting the time as follows:

SELECT CONVERT(CHAR(5), CONVERT(DATETIME, '10:00 PM'), 8);

Of course for an arbitrary date you can brute force it as follows:

SELECT RTRIM(MONTH(@myDate)) + '/' + RTRIM(DAY(@myDate)) + '/' + RTRIM(YEAR(@myDate))

Combining those of course translates to, in C#:

DateTime.Now.ToString("M/d/yyyy HH:mm");

In SQL Server 2012, you will be able to use almost identical syntax in T-SQL:

SELECT FORMAT(SYSDATETIME(), 'M/d/yyyy HH:mm');

Result at time of writing:

2/25/2012 00:38

(I blogged about the new FORMAT() capabilities last August when I first saw the feature in CTP3. It's pretty powerful stuff.)

You can see a table showing all of the valid styles to use with CONVERT in this FAQ article I wrote in 2003 . I also describe how you can make your own functions in a different FAQ article , but it doesn't explicitly cover the format you're after again because of the leading zeros.

This is probably not the most efficient way of doing this, but I think it should work:

declare @myDate varchar(50)
set @myDate = '2/24/2012 10:00 PM'

DECLARE @thisDate DATETIME
SET @thisDate = CAST(@myDate AS DATETIME)

SELECT CONVERT (NVARCHAR(10),@thisDate, 101) + ' ' + CONVERT(NVARCHAR(5), @thisDate, 8)

For SQL, you can try:

DECLARE @date DATETIME;
SET @date = CONVERT(DATETIME, @myDate, 20);
SELECT convert(varchar(10), @date, 101) + convert(varchar(5), @date, 114);

For C#,

DateTime convertedDate = DateTime.Parse('2/24/2012 10:00 PM');
String newDateStr = convertedDate.toString("MM/dd/yyyy HH:mm");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM