how to display time of three textbox in only one label? - c#

private void timer_click1(object sender, RoutedEventArgs e)
{
seconds = seconds - 1;
if (seconds == -1)
{
minutes = minutes - 1;
seconds = 59;
}
if (minutes == -1)
{
hours = hours - 1;
minutes = 59;
}
if (hours == 0 && minutes == 0 && seconds == 0)
{
timer.Stop();
}
string hhr = Convert.ToString(hours);
string minns = Convert.ToString(minutes);
string seccs = Convert.ToString(seconds);
}
I'm trying to create a countdown timer. I am stuck with hhr, minns and seccs because I have to display the countdown in one label not more. How can I pass these three text as hrr:minns:seccs?

There are probably better ways to get the remaining time but here is how you could use the string.Format method to display all three components in a single string:
private void timer_click1(object sender, RoutedEventArgs e)
{
seconds = seconds - 1;
if (seconds == -1)
{
minutes = minutes - 1;
seconds = 59;
}
if (minutes == -1)
{
hours = hours - 1;
minutes = 59;
}
if (hours == 0 && minutes == 0 && seconds == 0)
{
timer.Stop();
}
string hhr = Convert.ToString(hours);
string minns = Convert.ToString(minutes);
string seccs = Convert.ToString(seconds);
string s = string.Format("{0}:{1}:{2}", hhr, minns, seccs);
lbl.Text = s;
}
In C#6+ it's even eaiser:
string s = $"{hhr}:{minns}:{seccs}";

Related

how to calculated the age on birthday date for shamsi calendar with WPF in GridView

I have a grid view in wpf(C#) which contain Birth Day Date. I used bellow code for calculated the age for first row.
Now how to calculated the all row (ages)?
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string birth_day = "";
var query = from u in db.tbl_User select u;
var result = query.ToList();
if (result.Count > 0)
{
birth_day = result[0].BirthDayDate;
DateTime birthdaydate = DateTime.Parse(ShamsiToMiladi(birth_day));
DateTime todaydate = DateTime.Parse(ShamsiToMiladi(PublicVariable.TodayDate));
int days = todaydate.Day - birthdaydate.Day;
if (days < 0)
{
todaydate = todaydate.AddMonths(-1);
days += DateTime.DaysInMonth(todaydate.Year, todaydate.Month);
}
int months = todaydate.Month - birthdaydate.Month;
if (months < 0)
{
todaydate = todaydate.AddYears(-1);
months += 12;
}
int years = todaydate.Year - birthdaydate.Year;
MessageBox.Show(string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
years, (years == 1) ? "" : "s",
months, (months == 1) ? "" : "s",
days, (days == 1) ? "" : "s"));
}
Just a simple foreach:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var query = db.tbl_User.ToList();
if (!query.Any())return;
var results = new List<string>();
foreach(var user in query){
var birth_day = user.BirthDayDate;
DateTime birthdaydate = DateTime.Parse(ShamsiToMiladi(birth_day));
DateTime todaydate = DateTime.Parse(ShamsiToMiladi(PublicVariable.TodayDate));
int days = todaydate.Day - birthdaydate.Day;
if (days < 0)
{
todaydate = todaydate.AddMonths(-1);
days += DateTime.DaysInMonth(todaydate.Year, todaydate.Month);
}
int months = todaydate.Month - birthdaydate.Month;
if (months < 0)
{
todaydate = todaydate.AddYears(-1);
months += 12;
}
int years = todaydate.Year - birthdaydate.Year;
results.Add(
string.Format(
"{0} year{1}, {2} month{3} and {4} day{5}",
years, (years == 1) ? "" : "s",
months, (months == 1) ? "" : "s",
days, (days == 1) ? "" : "s"
)
);
}
}
Not enough rep to comment but to use foreach:
if (result.Count > 0)
{
birth_day = result[0].BirthDayDate;
becomes
foreach (var item in result)
{
// Use result.BirthDayDate

creating a game clock with custom time

I'm trying to make a GameClock like a real clock, but with a custom time.
The clock is running but it is delaying and I can't find the problem. Thanks for help.
IEnumerator Start()
{
while (true) {
Sec = DateTime.Now.Second;
if (Hour == 23 && Min == 59 && Sec == 0){
Hour = 0;
Min = 0;
} else if (Min == 59 && Sec == 0){
Min = 0;
Hour += 1;
} else if (Sec == 0) {
Min += 1;
}
yield return new WaitForSeconds (1f);
}
}
i think it should be like
while (true) {
Sec = DateTime.Now.Second;
if (Hour == 23 && Min == 59 && Sec == 59){
Hour = 0;
Min = 0;
} else if (Min == 59 && Sec == 59){
Min = 0;
Hour += 1;
} else if (Sec == 59) {
Min += 1;
}
yield return new WaitForSeconds (1f);
}
I don't get why you are doing all this work when you can just print out easily:
Debug.Log(System.DateTime.Now.ToString("hh:mm:ss"));
Debug.Log(System.DateTime.Now.Hour.ToString());
Debug.Log(System.DateTime.Now.Minute.ToString());
Debug.Log(System.DateTime.Now.Second.ToString());

Multiple while conditions

I want to output a timer in console which goes from 00h00m00s to 23h59m59s.
My code only outputs until 00h00m59s.
Must be the conditions in after the while, but i think it is correct.
Who knows how to solve this ?
static void Main(string[] args)
{
int uur = 0;
int min = 0;
int sec = 0;
while (uur != 23 && min!=60 && sec!=60)
{
if (sec == 60)
{
min++;
sec = 0;
}
if (min == 60)
{
uur++;
min = 0;
}
string strSec = String.Format("{0:00}", sec);
string strMin = String.Format("{0:00}", min);
string strUur = String.Format("{0:00}", uur);
Console.WriteLine(strUur + "h" + strMin + "m" + strSec + "s");
sec++;
}
Console.ReadLine();
}
Use the following condition:
while (uur != 23 || min != 59 || sec != 60)
You might also want to try this simpler approach:
int total_second_in_day = 24*60*60;
for (int second_in_day = 0; second_in_day < total_second_in_day; second_in_day++)
{
int uur = second_in_day / 3600;
int min = (second_in_day % 3600) / 60;
int sec = (second_in_day % 3600) % 60;
string strSec = String.Format("{0:00}", sec);
string strMin = String.Format("{0:00}", min);
string strUur = String.Format("{0:00}", uur);
Console.WriteLine(strUur + "h" + strMin + "m" + strSec + "s");
}
Console.ReadLine();
Although your question is basically about understanding while conditions this is how you could achieve printing all times:
using System;
public class Program
{
public static void Main()
{
var time = new TimeSpan(0,0,0,0);
var oneSec = new TimeSpan(0,0,0,1);
var wakeywakey = new TimeSpan(0,23,59,59);
while (time <= wakeywakey)
{
Console.WriteLine(time);
time += oneSec;
}
}
}

Javascript timer initializes on each postback

This is my script on aspx page which is used to initialize timer on page load.
<script type="text/javascript">
function display() {
var hours = document.getElementById('<%=HidH.ClientID %>');
var minutes = document.getElementById('<%=HidM.ClientID %>');
var seconds = document.getElementById('<%=HidS.ClientID %>');
if (hours.value == 00 && minutes.value == 00 && seconds.value == 00) {
PageMethods.ReturnQuestionId(1);
alert("Time Given For this Test is Over");
var newwindow = window.location.replace("frmResultCheck.aspx");
if (window.focus) { newwindow.focus() }
return false;
}
if (minutes.value < 10) {
minutes.value = minutes.value;
}
if (seconds.value <= 00) {
if ((hours.value == 00) && (minutes.value == 00))
seconds.value = 00;
else {
seconds.value = 60;
minutes.value -= 01;
}
}
if (minutes.value <= 00) {
if ((hours.value < 00) && (seconds.value < 00)) {
hours.value = minutes.value = seconds.value = 00;
}
else {
if ((hours.value == 00) && (seconds.value == 00))
hours.value = seconds.value = 00;
if ((hours.value > 00) && (minutes.value < 00)) {
minutes.value = 59;
hours.value -= 01;
}
}
}
if ((minutes.value <= -01) || (hours.value <= -01)) {
if (hours.value <= -01) {
minutes.value = 00;
hours.value += 01;
}
else
minutes.value -= 01;
seconds.value = 00;
minutes.value += 01;
}
else
if (seconds.value > 00)
seconds.value -= 01;
if (hours.value.length < 2) {
hours.value = "0" + hours.value;
}
if (minutes.value.length < 2) {
minutes.value = "0" + minutes.value;
}
if (seconds.value.length < 2) {
seconds.value = "0" + seconds.value;
}
document.getElementById('counter').value = hours.value + ":" + minutes.value +
":" + seconds.value;
setTimeout("display()", 1000);
if (document.getElementById('btnSubmit').onclick == true)
document.getElementById('counter').value = "";
}
display();
</script>
This is my aspx.cs page:
protected void Page_Load(object sender, EventArgs e)
{
int factor;
if (factor >= 60)
{
int b = factor / 60;
factor = factor % 60;
string time = Convert.ToString(b + ":" + factor);
if (factor < 10)
{
timer = TimeSpan.ParseExact(time, #"h\:m", null);
}
else
{
timer = TimeSpan.ParseExact(time, #"h\:mm", null);
}
}
else if (factor > 9 && factor < 60)
{
timer = TimeSpan.ParseExact(factor.ToString(), "mm", null);
}
else
{
timer = TimeSpan.ParseExact("0" + factor.ToString(), "mm", null);
}
HidH.Value = Convert.ToString(timer.Hours);
HidM.Value = Convert.ToString(timer.Minutes);
HidS.Value = Convert.ToString(timer.Seconds);
}
Everytime i click next button on page, timer goes back to the same time at which i clicked the next button. I want my timer to go on continuously even on postbacks.
In your C# Page_Load code, check if it is post-back before initializing the values. Initialize only if it is a first time load (i.e. !IsPostBack).
Like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// Your initializing code here
}
}

C# datetimepicker clear specific items

I have a Java application I'm trying to convert to C#. I have solved a fair bit of the program, but I have this clear method that troubles me:
private void checkCourts()
{
if (splMonth.getSelectedValue() != null && splDate.getSelectedValue() != null)
{
courtModel.clear();
Calendar booking = new GregorianCalendar();
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = new Scanner(splMonth.getSelectedValue().toString()).nextInt() - 1;
int date = new Scanner(splDate.getSelectedValue().toString()).nextInt();
int time = Integer.parseInt(cmbxTime.getSelectedItem().toString());
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
int currentDate = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int currentTime = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
booking.set(year, month, date, time, 0, 0);
if (month > currentMonth || (month == currentMonth && date > currentDate) || (month == currentMonth && date == currentDate && time > currentTime))
{
try
{
ArrayList<Reservation> rs = BookingManager.getInstance().getReservations();
Reservation r = new Reservation(booking);
ArrayList<String> courtNames = BookingManager.getInstance().getCourtsName();
for (int i = 0; i < rs.size(); i++)
{
r.getReservationTime().clear(Calendar.MILLISECOND);
rs.get(i).getReservationTime().clear(Calendar.MILLISECOND);
}
if (!rs.contains(r))
{
for (String c : courtNames)
{
courtModel.addElement(c);
}
}
else
{
for (String c : courtNames)
{
courtModel.addElement(c);
}
for (int i = 0; i < rs.size(); i++)
{
if (r.getReservationTime().getTime().equals(rs.get(i).getReservationTime().getTime()))
{
String courtName = BookingManager.getInstance().getNameById(rs.get(i).getCourtId());
courtModel.removeElement(courtName);
}
}
}
splCourt.setModel(courtModel);
}
catch (Exception e)
{
System.out.println("ERROR - " + e.getMessage());
}
}
else
{
JOptionPane.showMessageDialog(null, "Den valgte dato er ikke tilgængelig for booking.", "Advarsel", JOptionPane.INFORMATION_MESSAGE);
}
}
}
Well, the top for loop is the real issue, I think. I would like to remove the reservation times that already have been booked.
This is my first for loop try-out:
private void checkCourts()
{
DateTime current = DateTime.Now;
int year = Int32.Parse(DateTimePicker.Value.ToString("yyyy"));
int currentYear = current.Year;
int month = Int32.Parse(DateTimePicker.Value.ToString("MM"));
int currentMonth = current.Month;
int day = Int32.Parse(DateTimePicker.Value.ToString("dd"));
int currentDay = current.Day;
int time = (int)cmbxTime.SelectedItem;
int currentTime = current.TimeOfDay.Hours;
string date1 = year.ToString() + "," + month.ToString() + "," + day.ToString();
DateTime thisdate = DateTime.Parse(date1);
thisdate = thisdate.AddHours(time);
List<Reservation> rs = BookingManager.getInstance().getReservations();
Reservation r = new Reservation(thisdate);
List<string> courtNames = BookingManager.getInstance().getCourtsName();
if (month > currentMonth || (month == currentMonth && day > currentDay) ||
(month == currentMonth && day == currentDay && time > currentTime) && year >= currentYear)
{
try
{
for (int i = 0; i < rs.Count; i++)
{
r.ReservationTime = r.ReservationTime.AddTicks(-r.ReservationTime.Ticks % 10000000);
rs[i].ReservationTime = rs[i].ReservationTime.AddTicks(-rs[i].ReservationTime.Ticks % 10000000);
}
if (!rs.Contains(r))
{
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
}
else
{
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
for (int i = 0; i < rs.Count; i++)
{
if (r.ReservationTime.Equals(rs[i].ReservationTime))
{
String courtName = BookingManager.getInstance().getNameById(rs[i].CourtId);
lboxCourts.Items.Remove(courtName);
MessageBox.Show("is equal");
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
MessageBox.Show("Den valgte dato er ikke gyldig! - vær opmærksom på at hvis du vælger dags dato, at tidspunktet ikke kan være tidligere end nuværende tidspunkt!");
}
}
Hope you can clear my sight.. I have simply lost focus. I know of what I have see online - that datetimepicker is not that easy to edit. But then I would just edit the already booked item - to something like "already booked".
According to the docs, your Java code .clear(Calendar.MILLISECOND) is simply removing any milliseconds from the value. It's not doing anything with your application logic to remove the actual reservation times. It doesn't appear to involve any kind of DateTimePicker either.
Assuming in c# that the ReservationTime is a DateTime property, and r.ReservationTime is a different property than rs[i].ReservationTime, then you would need to do the following:
for (int i = 0; i < rs.Count; i++)
{
r.ReservationTime = r.ReservationTime.AddTicks(-r.ReservationTime.Ticks % 10000000);
rs[i].ReservationTime = rs[i].ReservationTime.AddTicks(-rs[i].ReservationTime.Ticks % 10000000);
}
There are a couple of points to note:
Java's Calendar class has resolution to the millisecond, so removing milliseconds would be truncating the value to the second.
DateTime in .Net has resolution to the tick. I tick is 100 nanoseconds, so there are 10,000,000 ticks in a second.
Therefore, you can't just clear the milliseconds, you have to clear by computing the remainder of ticks smaller than one second. Those are then subtracted from the original value, getting you the same result.
DateTime in .Net is immutable, so you can't just change one property. You have to compute a new value, and then assign it back to the original variable.
It ended up like this:
for (int i = 0; i < rs.Count; i++)
{
r.ReservationTime = r.ReservationTime;
rs[i].ReservationTime = DateTime.Parse(rs[i].ReservationTime.ToString());
if (thisdate.CompareTo(rs[i].ReservationTime) != 0)
{
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
}
else
{
lboxCourts.Items.Clear();
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
for (int j = 0; j < rs.Count; j++)
{
if (r.ReservationTime.Equals(rs[j].ReservationTime))
{
string courtName = BookingManager.getInstance().getNameById(rs[j].CourtId);
lboxCourts.Items.Remove(courtName);
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
MessageBox.Show("Den valgte dato er ikke gyldig! - vær opmærksom på at hvis du vælger dags dato, at tidspunktet ikke kan være tidligere end nuværende tidspunkt!");
}
}
Thank you for your help... now my method is removing the already booked courts ;-)
Kindest regards
Rasmus

Categories