ASP .NET C# Change from Military time to Standard Time - c#

I have this:
StringBuilder sb = new StringBuilder(time.Text);
if (DateTime.Parse(time.Text) > DateTime.Parse("12:00:00 AM")
&& DateTime.Parse(time.Text) < DateTime.Parse("11:59:59 AM"))
{
time.Text = time.Text + " AM";
}
else
{
time.Text = time.Text + " PM";
}
What I have now is 16:34 PM,
I want it to display 04:34 PM

Simply
string strTime = DateTime.Now.ToString(#"hh\:mm\:ss tt");
in your case, it will be:
time.Text=DateTime.Parse(time.Text).ToString(#"hh\:mm\:ss tt");
and make sure about custom formats, like HH is 24 hrs format, MM is for month

try
time.Text = DateTime.Parse(time.Text).ToString("hh:mm:ss tt");

public static string FormattedTime(this TimeSpan TimeIn24Hours)
{
String TimeIn12Hours = string.Empty;
if (TimeIn24Hours != null)
{
TimeIn12Hours = DateTime.MinValue.AddHours(TimeIn24Hours.Hours).AddMinutes(TimeIn24Hours.Minutes).ToString("hh:mm");
}
return TimeIn12Hours;
}

private void UpdateTime()
{
int hours, mins, sec;
string TimeofDate = "AM";
currentTime = DateTime.Now;
hours = Convert.ToInt32(currentTime.Hour.ToString());
mins = Convert.ToInt32(currentTime.Minute.ToString());
sec = Convert.ToInt32(currentTime.Second.ToString());
// lbCurrentTime.Text = currentTime.ToLongTimeString();
// label2.Text = hours.ToString() + ":" + mins.ToString() + ":" + sec.ToString();
if (hours >= 12)
{
hours = hours - 12;
TimeofDate = "PM";
}
else TimeofDate = "AM";
lbCurrentTime.Text = hours.ToString() + ":" + mins.ToString() + ":" + sec.ToString()+" "+TimeofDate;
}

Related

Calculate Daylight Saving Time in C#

How do you calculate Daylight Savings Time in C# with DateTime.Now? DST starts on the Second
Sunday in March. And ends on the first Sunday in November. These can be calculated thru the DayOfWeek in DateTime.
DayOfWeek dow;
string p = "3" + "/" + dy.ToString() + "/" + yr.ToString() + " " + "3" + ":" + mn.ToString() + ":" + sc.ToString();
DateTime start = DateTime.Parse(p);
p = "11" + "/" + dy.ToString() + "/" + yr.ToString() + " " + "1" + ":" + mn.ToString() + ":" + sc.ToString();
DateTime end = DateTime.Parse(p);
DateTime current;
for (dys = 1; dys <= 17; dys++)
{
p = "3" + "/" + dys.ToString() + "/" + yr.ToString() + " " + "3" + ":" + mn.ToString() + ":" + sc.ToString();
current = DateTime.Parse(p);
dow = current.DayOfWeek;
if ((mo == 3) && (aaa == 0) && (dow == DayOfWeek.Sunday))
{
aaa = 1;
}
if ((aaa == 1) && (dow == DayOfWeek.Sunday))
{
start = DateTime.Parse(p);
aaa = 2;
}
}
for (dye = 1; dye <= 14; dye++)
{
p = "11" + "/" + dye.ToString() + "/" + yr.ToString() + " " + "1" + ":" + mn.ToString() + ":" + sc.ToString();
current = DateTime.Parse(p);
dow = current.DayOfWeek;
if ((mo == 11) && (bbb == 0) && (dow == DayOfWeek.Sunday))
{
bbb = 1;
end = DateTime.Parse(p);
}
}
if ((start >= DateTime.Now) && (end <= DateTime.Now))
{
dsts = 0;
}
else
{
dsts = 1;
}
You can check these microsoft implementations. They already handle timezones and daylight saving time conversions. We do not need to implement them.
You need DateTimeOffset and TimeZoneInfo classes to deal with all these.
Always work with DateTimeOffset class instead of DateTime when dealing with timezones. https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset?view=net-6.0
link1: https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo?view=net-6.0
Convert time from one timezone to other https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.converttime?view=net-6.0
Something like below
DateTimeOffset thisTime = DateTimeOffset.Now;
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
bool isDaylight = tzi.IsDaylightSavingTime(thisTime);
DateTimeOffset timeInUtcTimeZone = TimeZoneInfo.ConvertTimeToUtc(thisTime);
DateTimeOffset timeInPstTimeZone = TimeZoneInfo.ConvertTimeToUtc(thisTime, tzi);
Similarly you can convert time from any timezone to any other timezone. And also the comparisons (Equals, greater than, less than) across the timezone will work well and handled by the framework.

I'm curious about the logic that checks only once at a certain time

I would like help.
There are some problems with the code.
I want to do only one inspection at a certain time every day.
In particular, the problem is the most serious in DateTime.Now.Hour == 11 part.
I am having difficulty checking certain times. I need to write code that can be checked only once at 11:00 in the whlie statement.
I created a license file and checked the date of the file.
public static CResult Dailytime(string date)
{
CResult result = new CResult();
if(result.nRet == 0)
{
while (true)
{
if (result.nRet == 1 || result.nRet == 2)
{
return result;
}
if (DateTime.Now.Hour == 11)
{
result = DailyCheckData(date);
if(result.nRet == 1 || result.nRet == 2)
{
return result;
}
}
System.Threading.Thread.Sleep(60 * 30 * 1000);
}
}
return result;
}
public static CResult DailyCheckData(string data)
{
CResult result = new CResult();
DateTime licenseDate = Convert.ToDateTime(data);
string dateNow = DateTime.Now.ToString("yyyy-MM-dd");
int compareDate = DateTime.Compare(Convert.ToDateTime(data), DateTime.Now);
if (licenseDate.ToString("yyyy-MM-dd") == dateNow)
{
result = ExpirationCertificate();
Console.WriteLine("Result = " + result.Result + " Msg = " + result.Msg + " nRet = " + result.nRet);
return result;
}
else
{
if (compareDate > 0)
{
result = TrueCertificate();
Console.WriteLine("Result = " + result.Result + " Msg = " + result.Msg + " nRet = " + result.nRet);
}
else if (compareDate <= 0)
{
result = ExpirationCertificate();
Console.WriteLine("Result = " + result.Result + " Msg = " + result.Msg + " nRet = " + result.nRet);
}
return result;
}
}
CResult class
nRet= 0 or 1 or 2
0 = fasle date
1 = false file
2 = true
Suggest or suggest ways to improve.
Can you try create a variable for DateTime.Now, after a line of code that value change.
DateTime licenseDate = Convert.ToDateTime(data);
string dateNow = DateTime.Now.ToString("yyyy-MM-dd");
int compareDate = DateTime.Compare(Convert.ToDateTime(data), DateTime.Now);
To
DateTime licenseDate = Convert.ToDateTime(data);
var now = DateTime.Now;
string dateNow = now.ToString("yyyy-MM-dd");
int compareDate = DateTime.Compare(licenseDate, now);
you shouldn't use Thread.Sleep() method for such a long duration. It is poor programming logic to make the thread sleep for such a long period.
What you can do to solve this is, is to make a Timer. There's an example attached in the link. A simple snippet to match your logic would be:
licenseStart = //setYours
lastCheck = DateTime.Now;
nextCheck = now.AddDays(1); // now.AddHours(1)
var timer = new Timer(o=>{/* Do work*/}, null, TimeSpan.Zero, nextCheck);
Hope it helps!
I asked about logic that can only loop once at 11 o'clock.
But I could not find the right answer and I found the answer.
I do not speak English well.
That's why others do not understand the intent of the question.
bool bOnce = true;
//bool s0nce = true;
while (true)
{
if (DateTime.Now.Hour == 11 && bOnce)
{
//run code
}
if (bOnce == true)
bOnce = false;
else
bOnce = true;
Thread.Sleep(10 * 60 * 1000);
}

Refactoring else if statement that returns current week from Wednesday

I am quite concerned about whether or not the code in CurrentRentWeek.cs is future-proof, is it good practice to have this many else if statements? If not, what would be the best way to refactor it?
MainWindow.Xaml.cs
public MainWindow()
{
InitializeComponent();
// Set current rent week
var datecheckObject = new CurrentRentWeek();
CurrentRentWeekTextBlock.Text = datecheckObject.DateCheck(CurrentRentWeekTextBlock.Text);
}
CurrentRentWeek.cs
public string DateCheck(string rentWeek)
{
if (_today.DayOfWeek == DayOfWeek.Monday)
{
_cRentWeekStart = _today.AddDays(-5);
_cRentWeekEnd = _today.AddDays(2);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +
_cRentWeekEnd.ToString("dd/MM/yyyy");
}
else if (_today.DayOfWeek == DayOfWeek.Tuesday)
{
_cRentWeekStart = _today.AddDays(-6);
_cRentWeekEnd = _today.AddDays(1);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +
_cRentWeekEnd.ToString("dd/MM/yyyy");
}
else if (_today.DayOfWeek == DayOfWeek.Wednesday)
{
_cRentWeekStart = _today.AddDays(0);
_cRentWeekEnd = _today.AddDays(7);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +
_cRentWeekEnd.ToString("dd/MM/yyyy");
}
else if (_today.DayOfWeek == DayOfWeek.Thursday)
{
_cRentWeekStart = _today.AddDays(-1);
_cRentWeekEnd = _today.AddDays(6);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +
_cRentWeekEnd.ToString("dd/MM/yyyy");
}
else if (_today.DayOfWeek == DayOfWeek.Friday)
{
_cRentWeekStart = _today.AddDays(-2);
_cRentWeekEnd = _today.AddDays(5);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +
_cRentWeekEnd.ToString("dd/MM/yyyy");
}
else if (_today.DayOfWeek == DayOfWeek.Saturday)
{
_cRentWeekStart = _today.AddDays(-3);
_cRentWeekEnd = _today.AddDays(4);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +
_cRentWeekEnd.ToString("dd/MM/yyyy");
}
else if (_today.DayOfWeek == DayOfWeek.Sunday)
{
_cRentWeekStart = _today.AddDays(-4);
_cRentWeekEnd = _today.AddDays(3);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +
_cRentWeekEnd.ToString("dd/MM/yyyy");
}
else
{
rentWeek = "";
}
return rentWeek;
}
You can start out with a generalized function to get the start of the week for any give date:
public static DateTime StartOfWeek(DateTime date)
{
while (date.DayOfWeek != DayOfWeek.Wednesday)
date = date.AddDays(-1);
return date;
}
Then you can simply call that method, add a fixed number of days to get to the end of the week, and create the string for those dates:
public string DateCheck()
{
var startOfWeek = StartOfWeek(_today);
var endOfWeek = startOfWeek.AddDays(7);
return string.Format("Current Rent Week: {0} - {1}",
startOfWeek.ToString("dd/MM/yyyy"),
endOfWeek.ToString("dd/MM/yyyy"));
}
You want that Wednesday is the beginning of the week? You can use this:
int daysDiff = (int)_today.DayOfWeek - (int)DayOfWeek.Wednesday;
if (daysDiff >= 0)
_cRentWeekStart = _today.AddDays(-daysDiff);
else
_cRentWeekStart = _today.AddDays(-(7 + daysDiff));
_cRentWeekEnd = _cRentWeekStart.AddDays(7);
This will return the last week's wednesday if today is "less" than wednesday which seems to be desired.
I think a switch statement would be much clearer for your case and give time savings but I doubt thats an issue.
switch (_today.DayOfWeek)
{
case DayOfWeek.Monday:
_cRentWeekStart = _today.AddDays(-5);
_cRentWeekEnd = _today.AddDays(2);
rentWeek = "Current Rent Week: " + _cRentWeekStart.ToString("dd/MM/yyyy") + " - " +_cRentWeekEnd.ToString("dd/MM/yyyy");
break;
case DayOfWeek.Tuesday:
//...
break;
//rest of cases
}

Time elapsed between two dates

I want to find the exact time elapsed between two dates with a condition that if any value is "0" its measurement units should disappear. for example if hours and minutes are o than the elapsed time should come like 1 day 40 seconds not like 1 day 0 hours 0 minutes 40 seconds.
TimeSpan elapsed = completdDate.Subtract(insertdDate);
int daysEl= elapsed.Days;
int hrsEl= elapsed.Hours;
int minsEl = elapsed.Minutes;
int secEl = elapsed.Seconds;
string totalTime = string.Empty;
string days = string.Empty;
string hours = string.Empty;
string mins = string.Empty;
string secs = string.Empty;
if (daysEl == 0 )
days = days.Replace(daysEl.ToString() , "");
else
days = daysEl.ToString();
if (hrsEl==0)
hours = hours.Replace(hrsEl.ToString() , "");
else
hours = hrsEl.ToString();
if (minsEl == 0)
mins = mins.Replace(minsEl.ToString(), "");
else
mins = minsEl.ToString();
if (secEl == 0)
secs = secs.Replace(secEl.ToString(), "");
else
secs = secEl.ToString();
totalTime = days + "days"
+ hours + "hours"
+ mins + "minutes"
+ secs + "seconds";
********************************Output*****************************
You can get rid of the intermediate strings and if statements:
totalTime =
(daysEl == 0 ? "" : (daysEl + " days "))
+ (hoursEl == 0 ? "" : (hoursEl + " hours "))
+ (minsEl == 0 ? "" : (minsEl + " minutes "))
+ (secsEl == 0 ? "" : (secsEl + " seconds "));
If you want to omit zero values, you're more likely looking at a formatting issue, not a calculation one, and it might be easier to use a StringBuilder.
var sb = new StringBuilder();
if (elapsed.Days != 0)
sb.AppendFormat("{0} days ", elapsed.Days);
if (elapsed.Hours != 0)
sb.AppendFormat("{0} hours ", elapsed.Hours);
if (elapsed.Minutes != 0)
sb.AppendFormat("{0} minutes ", elapsed.Minutes);
if (elapsed.Seconds != 0)
sb.AppendFormat("{0} seconds ", elapsed.Seconds);
if (sb.Length == 0)
return "instant!";
// get rid of the last space in there!
return sb.ToString().Substring(0,sb.Length-1);
By using a format, you're able to more succinctly bind the value with the units (ie "14 seconds") and thus put the whole portion into an if statement, bypassing the section entirely if it's zero.
void Main()
{
TimeSpan elapsed = DateTime.Now - DateTime.Now.AddDays(-1);
int daysEl= elapsed.Days;
int hrsEl= elapsed.Hours;
int minsEl = elapsed.Minutes;
int secEl = elapsed.Seconds;
var sb = new StringBuilder();
if (daysEl != 0 )
sb.Append(daysEl + " days ");
if (hrsEl != 0)
sb.Append(hrsEl + " hours ");
if (minsEl != 0)
sb.Append(minsEl + " mins ");
if (secEl != 0)
sb.Append(secEl + " secs ");
string totalTime = sb.ToString();
Console.WriteLine (totalTime);
}

calculate difference between 2 dates from datetimepicker [duplicate]

This question already has answers here:
date difference using datepicker in wpf
(2 answers)
Closed 8 years ago.
I want to calculate the differences between two dates, one picked form dateTimePicker1 and the other one 20 February of 2014 and store it in a string to added to my array and be able to display it in another form
THIS is my code:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
int differenceInDays = ts.Days;
string differenceAsString = differenceInDays.ToString();
return ts;
}
public class Patient
{
public string patientidString;
public string firstNameString;
public string lastNameString;
public string dateString;
public string differenceAsString;
public Patient()
{
patientidString = "";
firstNameString = "";
lastNameString = "";
dateString = "";
}
}
//Array
Patient[] patientInfo = new Patient[10];
private void button1_Click(object sender, EventArgs e)
{
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker1.Value);
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0)
{
MessageBox.Show(" Patient id, first name and last name cannot be empty");
}
else
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidString = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
patientInfo[itemCountInteger].dateString = dateTimePicker1.Text;
string names = patientInfo[itemCountInteger].patientidString + " " + patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
//Search Button search a patients name and display his surname in the label if patient is found display his surname
private void button2_Click(object sender, EventArgs e)
{
int intTest = 0;
for (int x = 0; x < patientInfo.Length; x++)
{
if (textBox4.Text == patientInfo[x].patientidString)
{
label6.Text = (patientInfo[x].firstNameString + " " + patientInfo[x].lastNameString);
PatientForm patientform = new PatientForm();
patientform.Show();
patientform.label6.Text = (patientInfo[x].patientidString);
patientform.label7.Text = (patientInfo[x].firstNameString);
patientform.label8.Text =(patientInfo[x].lastNameString);
patientform.dateTimePicker1.Text = (patientInfo[x].dateString);
patientform.label9.Text = (patientInfo[x].differenceAsString);
intTest = 1;
break;
}
}
if (intTest == 0)
{
label6.Text = ("not found");
}
}
DateTime febDate = new DateTime(2014, 2, 20);
DateTime pickerDate = myDateTimePicker.Value;
TimeSpan tspan = febDate - pickerDate;
int differenceInDays = tspan.Days;
string differenceAsString = differenceInDays.ToString();
If differenceInDays < 0 then multiply it by -1.
Note: In this case it's very easy to get the difference in hours, minutes or seconds as well.
Here's an example of the above code in it's own method:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
return ts;
}
And when you want to trigger this method:
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker.Value);
//Now you can do what you want with the TimeSpan.
int differenceInDays = difference.Days;
int differenceInHours = difference.Hours;
Console.WriteLine(differenceInDays.ToString());
DateTime a = new DateTime.Parse(string);
Console.WriteLine(datePicker.Value.Subtract(a).TotalMinutes);
You can subtract any two dates and it will work.
DateTime date1 = new DateTime(2014,02,20);
DateTime date2 = dateTimePicker1.Value as DateTime;
TimeSpan difference = date1 - date2; //dunno what difference you need so you can swap these

Categories