Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format DateTime with text in-between

I want to format my DateTime object in a specific way. This is the basis:

DateTime dt = new DateTime(2018, 11, 20, 15, 30, 5, 0);
Debug.WriteLine(dt.ToString("ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture));

The output will be Tue Nov 20 15:30:05 +01:00 2018. This is ALMOST what I want: instead of the +01:00 I want the value of a string variable myText.

So if myText has the value "hello world", the output should be:

Tue Nov 20 15:30:05 hello world 2018

So my question is simply: What do I need to write to get formatting (except the zzz part) but with the value of a string variable in-between?

I tried dt.ToString("ddd MMM dd HH:mm:ss " + myText + " yyyy", CultureInfo.InvariantCulture), but for myText = "hello world" it will output

Tue Nov 20 15:30:05 3ello worl20 2018

i.e. the content of myText will be considered as formatting, just as the rest. But I want the content of myText to be taken literally instead.

like image 365
Kjara Avatar asked Dec 12 '25 01:12

Kjara


1 Answers

You can wrap your text in quotes (') and it will output your desired format.

dt.ToString("ddd MMM dd HH:mm:ss '" + myText + "' yyyy", CultureInfo.InvariantCulture);

// output
Tue Apr 02 12:37:49 hello world 2019

It's matching the h from hello and the d from world which is why you were seeing that result.

You may look at Custom date and time format strings from microsoft which has a section (near the bottom) regarding quotation marks. The inclusion of quotes (either single ' or double ") in a DateTime format (or Numeric format) introduces a string literal in the resulting string format.

As @Dmitry points out in a comment, you may need to use myText?.Replace("'", "''") if ' appear in your string. Another option is to use double quotes and escape as usual:

dt.ToString("ddd MMM dd HH:mm:ss \"" + myText + "\" yyyy", CultureInfo.InvariantCulture);
like image 123
haldo Avatar answered Dec 14 '25 16:12

haldo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!