Reputation: 14024
Please have a look on the code below:
DateTime timerTest = timerView;
txbTimer.Text = timerTest.Day + "/" + timerTest.Month + "/" + timerTest.Year + " " + timerTest.Hour + ":" + timerTest.Minute;
I am suppose to get Date and Time in the txbTimer
Which I am getting. If the date is 14/8/2015 14:10
But when the time (minute) is 01 - 09 the txbTimer
will become 14/8/2015 14:1 in this case I wanted the expected output like 14:01 and not 14:1
Please help me
My Code is
I think the lines which adds hours and days might be changing so here is the updated code.
DateTime timerView = DateTime.Now;
DateTime timerTest = timerView;
if(robHour.Checked == true)
timerTest = timerView.Add(new TimeSpan(0, 1, 0, 0));
else if(robDay.Checked == true)
timerTest = timerView.Add(new TimeSpan(1, 0, 0, 0));
txbTimer.Text = timerTest.ToString(); //timerTest.Day + "/" + timerTest.Month + "/" + timerTest.Year + " " + timerTest.Hour + ":" + timerTest.Minute.ToString();
Upvotes: 4
Views: 9809
Reputation: 3364
To get the minute component of a DateTime as a number from 00 through 59, use the "mm" custom format specifier.
DateTime dateTime = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(dateTime.ToString("mm"));
// Displays "01"
Documentation:
Upvotes: 0
Reputation:
This will solve the issue you are facing
DateTime timerView = DateTime.Now;
DateTime timerTest = timerView;
if(robHour.Checked == true)
timerTest = timerView.Add(new TimeSpan(0, 1, 0, 0));
else if(robDay.Checked == true)
timerTest = timerView.Add(new TimeSpan(1, 0, 0, 0));
txbTimer.Text = timerTest.Day +
"/" + timerTest.Month + "/" +
timerTest.Year + " " + timerTest.Hour +
":" + timerTest.Minute.ToString("D2");
Upvotes: 2
Reputation: 32481
Use this
timerTest.Minute.ToString("D2");
For more formatting follow this link
Here are examples provided by MSDN
1234.ToString("D") -> 1234 (-1234).ToString("D6") -> -001234
Upvotes: 10
Reputation: 5990
DateTime timerTest = timerView;
var result = timerTest.ToString("dd/M/yyyy hh:mm");
/*
dd -> two digit day
M -> one digit month
yyyy -> four digit year
hh -> two digit hour
mm -> two digit minute
*/
HH:(00-23) will look like 00, 01..23.
hh:(01-12 in AM/PM) will look like 01, 02..12.
Upvotes: 6
Reputation: 98740
Minute
property of a DateTime
returns integer. That means it can't have any leading zeros.
You can use mm
format specifier to get it's string representation with leading zeros for single digit minutes.
By the way, your method is not a good way to get string representation of a DateTime. Using ToString()
method with a culture that have /
as a DateSeparator
and :
as a TimeSeparator
(eg: InvariantCulture
) is better.
txbTimer.Text = timerTest.ToString("dd/M/yyyy HH:mm", CultureInfo.InvariantCulture);
Here a demonstration
.
Upvotes: 4
Reputation: 2541
You might want to use DateTime Format strings:
txbTimer.Text = timerTest.ToString("d/M/yyyy HH:mm");
Working example here.
Also take a look at one of the pre-defined standard formats.
Upvotes: 1