I am creating my first win form application, written in C#. I have added a little bit of code to display the current date and time on the first tab page as below:
private void Form1_Load(object sender, EventArgs e)
{
// connect to database
c = new Connection();
connect.ConnectionString = c.getConnection();
//deals with date and time
Timer tmr = new Timer();
tmr.Interval = 1000;//ticks every 1 second
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Start();
}
private void tmr_Tick(object sender, EventArgs e)
{
labeltime.Text = DateTime.Now.ToString(" Todays Date: dd/MM/yyyy\n\n Current Time: HH:mm:ss");
}
The output in not correct however. The date and time are correct and ticking away nicely but where I want it to display "Todays Date:" it is messy like " To15a1342 (42 being the seconds from the time, ticking away) and the "Current Time" reads CuRRenP Ti50e:
Does it matter that I am in the UK? Would this require me to use different code or something?
Anonymous User
18-Dec-2013Your text is being interpreted as formatting strings, as explained in DateTime.ToString(string format):
The format parameter should contain either [...] a custom format pattern (see Custom Date and Time Format Strings)
Only unrecognized characters are printed as-is, but as you noticed for example the s gets replaced by the value of Seconds.
To let ToString() ignore your text, you need to escape the literals, preferably with single quotes (') (the alternative is a backslash in front of each literal):
string dateTimeString = DateTime.Now
.ToString("' Todays Date: 'dd/MM/yyyy'\n\n Current Time: 'HH:mm:ss");
Or build up the string from separate parts:
var now = DateTime.Now;
string dateTimeString = "' Todays Date: ";
dateTimeString += now.ToString("dd/MM/yyyy");
dateTimeString += "\n\n Current Time: ";
dateTimeString += now.ToString("HH:mm:ss");
Above string concatenation example can in turn be simplified as @Rohit's answer demonstrates.