DateTime format not showing correctly - c#

Firstly, apologies for asking a question that has been asked before, but even with the examples I am not getting the desired results.
All I am trying to do is display the current time, which it does, but I noticed that the datetime format was 9:5:6 instead of 09:05:06. I read the examples about formatting DateTime but it doesn't work for some reason. Can anyone shed any light on where I am going wrong?
Thanks for your help as always.
public MainWindow()
{
InitializeComponent();
DispatcherTimer dispatchTimer = new DispatcherTimer();
dispatchTimer.Tick += new EventHandler(dispatchTimer_Tick);
dispatchTimer.Interval = new TimeSpan(0, 0, 1);
dispatchTimer.Start();
}
private void dispatchTimer_Tick(object sender, EventArgs e)
{
var hour = DateTime.Now.Hour.ToString();
var min = DateTime.Now.Minute.ToString();
var sec = DateTime.Now.Second.ToString();
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}

Just use a custom format string:
var today = DateTime.Now.ToString("HH:mm:ss");
Or the standard one:
var today = DateTime.Now.ToString("T");

string now = DateTime.Now.ToString("HH:mm:ss");
Check TimeZoneInfo Class for more detailed globalization.

I think there are many ways to tackle this issue.
Personally, and to keep things simple, I would do it this way:
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string wTime = DateTime.Now.ToString("HH:mm:ss");
// OR THIS WAY
string wTime2 = DateTime.Now.ToString("T");
label1.Content = wTime;
textBlock1.Text = wTime;
button1.Content = wTime;
}
But if you want for some reasons to keep your initial logic then this would do it too.
private void dispatchTimer_Tick(object sender, EventArgs e)
{
string hour = DateTime.Now.Hour.ToString("00");
string min = DateTime.Now.Minute.ToString("00");
string sec = DateTime.Now.Second.ToString("00");
var today = hour + ":" + min + ":" + sec;
label1.Content = today;
textBlock1.Text = today;
button1.Content = today;
}
You may also wish to look at this http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

Related

Clear the DateTimePicker control in c# winfoms

I want to clear the DateTimePicker control value when i click on clear button but i can't do that with simple double qoutes, So please help me
tbAddress.Text = "";
dtpBirth.Value = "";
cBoxGender.SelectedIndex = -1;
This should do the trick
dtpBirth.CustomFormat = " ";
dtpBirth.Format = DateTimePickerFormat.Custom;
it will clear the input box.
try is
dateTimePickerDOB.Value = DateTimePicker.MinimumDateTime
in this your date and time going to be minimum date and time in your DateTimePicker and dateTimePickerDOB mean your Design(name)
or
try this for clear the date
dateTimePicker_dob.Text = string.Empty;
in here dateTimePickerDOB mean your Design(name)
The DateTimePicker.Value is from type DateTime and not a String.
dtpBirth.Value = DateTime.Now;
You can do this:
private void DateTimePicker1_ValueChanged(object sender, EventArgs e)
{
if (dateTimePicker1.Value == DateTimePicker.MinimumDateTime)
{
dateTimePicker1.Value = DateTime.Now; // This is required in order to show current month/year when user reopens the date popup.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " ";
}
else
{
dateTimePicker1.Format = DateTimePickerFormat.Short;
}
}
private void Clear_Click(object sender, EventArgs e)
{
dateTimePicker1.Value = DateTimePicker.MinimumDateTime;
}

Disable all dates after some months from a certain date Android DatePicker

I have two DatePickers in my app. First, shows the FromDate which is CurrentDate+1, the second shows the ToDate ie. FromDate+1.
I have got the above scenario working. But now I want to disable all the dates after 6 months from the FromDate.
I tried doing the following,but the calender then shows 01/01/1970 as the current date.
BookingActivity.cs
void IbtnToDate_Click(object sender, EventArgs e)
{
toDateClicked = true;
fromDateClicked = false;
dateFragment = new DatePickerFragment(this, DateTime.Parse (editFromDate.Text.ToString ()).AddDays (1), this, DateTime.Parse (editFromDate.Text.ToString ()));
dateFragment.Show(FragmentManager, null);
}
void IbtnFromDate_Click(object sender, EventArgs e)
{
fromDateClicked = true;
toDateClicked = false;
dateFragment = new DatePickerFragment(this, date.AddDays (1), this, date.AddDays (1));
dateFragment.Show(FragmentManager, null);
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
var date1 = new DateTime(year, monthOfYear + 1, dayOfMonth);
if (fromDateClicked)
UpdateFromDate (date1);
else if (toDateClicked) {
UpdateToDate (date1);
}
}
DatePickerFragment.cs
public class DatePickerFragment : DialogFragment
{
private readonly Context _context;
private DateTime _date, _minDate, _maxDate;
private readonly Android.App.DatePickerDialog.IOnDateSetListener _listener;
public DatePickerFragment(Context context, DateTime date, Android.App.DatePickerDialog.IOnDateSetListener listener, DateTime minDate)
{
_context = context;
_date = date;
_listener = listener;
_minDate = minDate;
}
public override Dialog OnCreateDialog(Bundle savedState)
{
var dialog = new Android.App.DatePickerDialog(_context, _listener, _date.Year, _date.Month - 1, _date.Day);
dialog.DatePicker.MinDate =_minDate.AddDays (1).Millisecond;
dialog.DatePicker.MaxDate = _date.AddMonths(6).Millisecond;
return dialog;
}
}
How can I achieve it? Any help would be appreciated.
You can use setMaxDate and can do something like:
1- Get the date from _mindate string:
String dateString = "03/26/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2- Get date of 6 months from min_date:
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(convertedDate);
cal.add(Calendar.MONTH, 1);
Date 6MonthsFromCurrentDate = cal.getTime();
3- Restricting the datePicker to that date:
datePickerDialog.getDatePicker().setMaxDate(6MonthsFromCurrentDate.getTime());
Use these lines of code.
Calendar ci = Calendar.getInstance();
String CiDateTime = ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 7) + "-" + //for 6 month future
ci.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date d;
try {
d = f.parse(CiDateTime);
long milliseconds = d.getTime();
_date.setMaxDate(milliseconds);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to Add Custom Time Format?

I am making a NetcafeProgram in C# and I want to get the current DateTime. I want my output like this (hr.mins)"0.25". I have the current DateTime but I want to show it like this (hr.mins)"0.25" in the labelTime_1 but it is not working. This is the command which I used
starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
and I changed it to
starttime_1 = DateTime.Now.ToString("h.mm");
and then I wanted to get the duration like this
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
but it gives me errors.
Here is a Screenshot of My Formv:
I want the time to get posted On that Time Elapsed Label but it doesn't work. Here is the coding of BtnStop1
private void btnStop_1_Click(object sender, EventArgs e)
{
//string duration = Convert.ToInt32(((starttime_1) - (endtime_1)));
gbx_1.BackColor = Color.LimeGreen;
btnStop_1.Enabled = false;
//endtime_1 = DateTime.Now.ToString("h:mm:ss tt");
//TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
endtime_1 = DateTime.Now.ToString("h.mm tt");
TimeSpan duration = DateTime.Parse(endtime_1).Subtract(DateTime.Parse(starttime_1));
lblTime_1.Text = Convert.ToString(duration);
string var = "Cabin One is Free";
btnStart_1.Enabled = true;
HP_1.Enabled = true;
CR_1.Enabled = true;
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
}
Coding of BtnStart
private void btnStart_1_Click(object sender, EventArgs e)
{
gbx_1.BackColor = Color.Red;
btnStart_1.Enabled = false;
//starttime_1 = DateTime.Now.ToString("h:mm:ss tt");
starttime_1 = DateTime.Now.ToString("h.mm tt");
lblTime_1.Text = "CountingTime";
string var = "Cabin One is Occupied";
reader = new SpeechSynthesizer();
reader.SpeakAsync(var);
HP_1.Enabled = false;
CR_1.Enabled = false;
}
Here Are My Variables
public string starttime_1;
public string starttime_2;
public string starttime_3;
public string starttime_4;
public string starttime_5;
public string starttime_6;
public string endtime_1;
public string endtime_2;
public string endtime_3;
public string endtime_4;
public string endtime_5;
public string endtime_6;
I would strongly suggest changing your variable types to DateTime?. It is better to store data in its native type and then do the convert to string on display. This way, when you want the duration, you are not parsing back to DateTime. You can handle any rounding you want on the base data.
So, your conversion to string should be at the highest level of you stack. It will keep your code cleaner and make it easier to refactor the logic away from the UI later if appropriate.
Not really sure I understand all this parsing but if you're just trying to record start and stop times and output a timespan I would do as Jon Skeet recommend with the stopwatch. Something along these lines looks like what you're going for but a bit cleaner.
// Build stopwatch and lists
Stopwatch sw = new Stopwatch();
List<string> startTimes = new List<string>();
List<string> endTimes = new List<string>();
private void startBtn_Click(object sender, EventArgs e)
{
// Start stopwatch and record start time
sw.Start();
startTimes.Add(DateTime.Now.ToString("h.mm"));
}
private void stopBtn_Click(object sender, EventArgs e)
{
// Stop stopwatch
sw.Stop();
// Record stop time and reset stopwatch
endTimes.Add(DateTime.Now.ToString("h.mm"));
sw.Reset();
// Output timespan
outputLbl.Text = sw.Elapsed.ToString();
}

Passing data from one button click event to another button click event

Below is my code. I want to capture the difference between two timestamps at two different button clicks, i.e., i want the "startTime" of btnStartTime_click event to be used in btnEndTime_click event.
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
lblStartTime.Text = startTime.ToString("HH:mm:ss tt");
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is "+workDuration);
}
Just make your startTime outside the local scope:
DateTime startTime;
protected void btnStartTime_Click(object sender, EventArgs e)
{
startTime = DateTime.Now;
lblStartTime.Text = startTime.ToString("HH:mm:ss tt");
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is "+workDuration);
}
Since this concerns a web application, you must store the startTime in a way where it can be restored on a later post back.
Here's a quick sample that should work using ViewState:
private const string StartTimeViewstateKey = "StartTimeViewstateKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
ViewState[StartTimeViewstateKey] = startTime.ToString(CultureInfo.InvariantCulture);
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Parse((string)ViewState[StartTimeViewstateKey], CultureInfo.InvariantCulture);
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is " + workDuration);
}
Alternatively you could use session state:
private const string StartTimeSessionKey= "StartTimeSessionKey";
protected void btnStartTime_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
Session[StartTimeSessionKey] = startTime;
}
protected void btnEndTime_Click(object sender, EventArgs e)
{
var startTime = (DateTime)Session[StartTimeSessionKey];
var workDuration = DateTime.Now.Subtract(startTime).TotalMinutes;
lblEndTime.Text = ("The Work duration is " + workDuration);
}

YouTube Tutorial Can't select second Item in Listview (Invalid argument)

I am trying to follow along and complete this address book tutorial on YouTube Address Book Tutorial
But I have ran into a snag that I don't understand. Following along I cannot find the difference in code. So I am thinking it must be a property setting that I am missing. When I test populate the list I can select the first item. But when I select the second item the debugger kicks out an error
invalid argument=value of '0' is not valid for 'index'
Can someone tell me why this error is thrown? Listening to the video it sounds like the 0 in the code is to tell the list that you can only select one item at a time. Unfortunately I haven't been able to figure out why his code works and mine does not.
private void button3_Click(object sender, EventArgs e)
{
person p = new person(); // creates new string array
p.Name = textBox1.Text; // name
p.StreetAddress= textBox3.Text; // address
p.Email = textBox2.Text; // email
p.Birthday = dateTimePicker1.Value; //birthday
p.AdditionalNotes = textBox4.Text; // any notes
people.Add(p); // tells the the above data to be added to the people list.
listView1.Items.Add(p.Name); // makes its show on the listview of the main box.
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
dateTimePicker1.Value = DateTime.Now;
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = people[listView1.SelectedItems[0].Index].Name; //Debugger points error here.
textBox2.Text = people[listView1.SelectedItems[0].Index].Email;
textBox3.Text = people[listView1.SelectedItems[0].Index].StreetAddress;
textBox4.Text = people[listView1.SelectedItems[0].Index].AdditionalNotes;
dateTimePicker1.Value = people[listView1.SelectedItems[0].Index].Birthday;
}
class person
{
public string Name
{
get;
set;
} ...
}
I managed to speak with the program creator. The solution is to check and handle no selection. So Adding an If statement solved the Issue.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0) return; // This line added will solve the problem
textBox1.Text = people[listView1.SelectedItems[0].Index].Name;
textBox2.Text = people[listView1.SelectedItems[0].Index].Email;
textBox3.Text = people[listView1.SelectedItems[0].Index].StreetAddress;
textBox4.Text = people[listView1.SelectedItems[0].Index].AdditionalNotes;
dateTimePicker1.Value = people[listView1.SelectedItems[0].Index].Birthday;
}

Categories