I have a 12 hour clock that calculates the difference between two times in decimal. It runs through the loop below but after testing I saw that when I type in a time between 12:00 and 12:59 (AM or PM) it posts the completely wrong time. The problem is that the 12th hour is a special case and doesn't need to have 12 added or subtracted from it. How can I fix this so it posts the correct time in decimal?
Also since I'm posting this I have another question; how can I easily calculate the total time in decimal?
Here's a picture of the GUI so you have an idea of what we're dealing with.
http://imgur.com/y7JezcC
protected void CalculateButton_Click(object sender, EventArgs e)
{
//Initializing
TextBox[] textboxesIn = new TextBox[7];
TextBox[] textboxesOut = new TextBox[7];
DropDownList[] dropdownIn = new DropDownList[7];
DropDownList[] dropdownOut = new DropDownList[7];
Label[] labels = new Label[7];
//Week 1 in textboxes
textboxesIn[0] = MondayW1InTextBox;
textboxesIn[1] = TuesdayW1InTextBox;
textboxesIn[2] = WednesdayW1InTextBox;
textboxesIn[3] = ThursdayW1InTextBox;
textboxesIn[4] = FridayW1InTextBox;
textboxesIn[5] = SaturdayW1InTextBox;
textboxesIn[6] = SundayW1InTextBox;
//Week 1 out textboxes
textboxesOut[0] = MondayW1OutTextBox;
textboxesOut[1] = TuesdayW1OutTextBox;
textboxesOut[2] = WednesdayW1OutTextBox;
textboxesOut[3] = ThursdayW1OutTextBox;
textboxesOut[4] = FridayW1OutTextBox;
textboxesOut[5] = SaturdayW1OutTextBox;
textboxesOut[6] = SundayW1OutTextBox;
//Week 1 in drop down list
dropdownIn[0] = MondayW1InDropDown;
dropdownIn[1] = TuesdayW1InDropDown;
dropdownIn[2] = WednesdayW1InDropDown;
dropdownIn[3] = ThursdayW1InDropDown;
dropdownIn[4] = FridayW1InDropDown;
dropdownIn[5] = SaturdayW1InDropDown;
dropdownIn[6] = SundayW1InDropDown;
//Week 1 out drop down list
dropdownOut[0] = MondayW1OutDropDown;
dropdownOut[1] = TuesdayW1OutDropDown;
dropdownOut[2] = WednesdayW1OutDropDown;
dropdownOut[3] = ThursdayW1OutDropDown;
dropdownOut[4] = FridayW1OutDropDown;
dropdownOut[5] = SaturdayW1OutDropDown;
dropdownOut[6] = SundayW1OutDropDown;
//Week 1 labels
labels[0] = MondayW1Label;
labels[1] = TuesdayW1Label;
labels[2] = WednesdayW1Label;
labels[3] = ThursdayW1Label;
labels[4] = FridayW1Label;
labels[5] = SaturdayW1Label;
labels[6] = SundayW1Label;
for (int i = 0; i < 7; i++)
{
DateTime dt = DateTime.ParseExact(textboxesIn[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
string timestring = dt.ToString("h:mm");
labels[i].Text = timestring;
DateTime timeIn = DateTime.ParseExact(textboxesIn[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
DateTime timeOut = DateTime.ParseExact(textboxesOut[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
if (dropdownIn[i].SelectedValue == "PM")
{
timeIn = timeIn.AddHours(12);
}
if (dropdownOut[i].SelectedValue == "PM")
{
timeOut = timeOut.AddHours(12);
}
labels[i].Text = (timeOut - timeIn).TotalHours.ToString("f2");
}
}
Try
DateTime timeIn = DateTime.ParseExact(textboxesIn[i].Text.PadLeft(4, '0') + dropdownIn[i].SelectedValue.Text, "hhmm tt", CultureInfo.InvariantCulture);
You have to change HH to hh because you cant Parse 12AM to HH.
After that you can timeOut - timeIn without problem.
In every case, when you write 1 to 11, it would be AM by default and you can sum 12 hs, but when you write 12 always will be PM (AM would be 00), So:
1PM + 12 = 13
2PM + 12 = 14
..
11PM + 12 = 23
//Now your strange result:
12:45(PM) + 12 = 24:45 => 00:45 but one day after
3:00(PM) + 12 = 15
15hs (Day 0) - 00:45 (Day 1) is your negative result.
An easy way is resting 12hs when 12 is the case.
for (int i = 0; i < 7; i++)
{
DateTime dt = DateTime.ParseExact(textboxesIn[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
string timestring = dt.ToString("h:mm");
labels[i].Text = timestring;
DateTime timeIn = DateTime.ParseExact(textboxesIn[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
DateTime timeOut = DateTime.ParseExact(textboxesOut[i].Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
if(timeIn.Hour == 12) timeIn = timeIn.AddHours(-12); //a easy way
if (dropdownIn[i].SelectedValue == "PM")
{
timeIn = timeIn.AddHours(12);
}
if (dropdownOut[i].SelectedValue == "PM")
{
timeOut = timeOut.AddHours(12);
}
labels[i].Text = (timeOut - timeIn).TotalHours.ToString("f2");
}
Related
The problem is that I need to find each Saturday and Friday night and charge them $140 on Friday or Saturday. Should I use a while loop?
DateTime ArrivalDate = DateTime.Parse(txtArrivalDate.Text);
DateTime DepartureDate = DateTime.Parse(txtDepartureDate.Text);
TimeSpan numberOfNights = DepartureDate.Subtract(ArrivalDate);
decimal nights = numberOfNights.Days;
txtNights.Text = nights.ToString();
//txtTotalPrice
decimal pricePerNight = 120.00m;
decimal totalNight = nights * pricePerNight;
txtTotalPrice.Text = "$" + totalNight.ToString();
txtAvgPrice.Text = "$" + pricePerNight.ToString();
// finds the fridays
decimal morePricePerNight = 140.00m;
int i = 0;
// while loop
while (ArrivalDate.DayOfWeek != DayOfWeek.Friday)
{
ArrivalDate = ArrivalDate.AddDays(1);
}
while (DepartureDate.DayOfWeek != DayOfWeek.Friday)
{
DepartureDate = DepartureDate.AddDays(1);
}
Why not to use just a one while loop?
I guess you can write the following code:
var date = DepartureDate;
while (date < ArrivalDate)
{
if (date.DayOfWeek == DayOfWeek.Friday || date.DayOfWeek == DayOfWeek.Saturday)
{
totalNight += 140.00m;
}
date = date.AddDays(1);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class calenderdisp : System.Web.UI.Page
{
DateTime dt = DateTime.Now;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack )
{
if (ddlweeklist.SelectedItem.Text == "Today")
{
txtstart.Text = DateTime.Now.ToString("dd/MM/yyyy");
Txtend.Text = DateTime.Today.ToString("dd/MM/yyyy");
}
}
}
protected void ddlweeklist_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlweeklist.SelectedItem.Text == "This Week")
{
int st = DayOfWeek.Sunday - dt.DayOfWeek;
int en = DayOfWeek.Saturday - dt.DayOfWeek;
txtstart.Text = dt.AddDays(st).ToString("dd/MM/yyyy");
Txtend.Text = dt.AddDays(en).ToString("dd/MM/yyyy");
}
if (ddlweeklist.SelectedItem.Text == "Next Week")
{
DateTime dt1 = dt.AddDays(7);
int st = DayOfWeek.Sunday - dt1.DayOfWeek;
int en = DayOfWeek.Saturday - dt1.DayOfWeek;
txtstart.Text = dt1.AddDays(st).ToString("dd/MM/yyyy");
Txtend.Text = dt1.AddDays(en).ToString("dd/MM/yyyy");
}
if (ddlweeklist.SelectedItem.Text == "Last Week")
{
DateTime dt2 = dt.AddDays(-7);
int st = DayOfWeek.Sunday - dt2.DayOfWeek;
int en = DayOfWeek.Saturday - dt2.DayOfWeek;
txtstart.Text = dt2.AddDays(st).ToString("dd/MM/yyyy");
Txtend.Text = dt2.AddDays(en).ToString("dd/MM/yyyy");
}
if (ddlweeklist.SelectedItem.Text == "This Month")
{
DateTime stmonth = new DateTime(dt.Year, dt.Month, 1);
DateTime enmnth = new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
txtstart.Text = stmonth.ToString("dd/MM/yyyy");
Txtend.Text = enmnth.ToString("dd/MM/yyyy");
txtnodm.Text = DateTime.DaysInMonth(dt.Year, dt.Month).ToString();
Isleap();
}
}
}
now got the answer...thank u .........but how this can be done using java script as i was very much interested to learn it so please kindly give suggestions to this code to be written in javascript
and i will be glad if u let me know the standard book to be followed to learn java script
Please try with the below code snippet.
DateTime dt = DateTime.Now; //Your Date
DateTime start = new DateTime(dt.Year, dt.Month, 1); //First Date of the month
DateTime end = start.AddMonths(1).AddDays(-1); //Last Date of the month
string startDay = start.DayOfWeek.ToString(); //First weekday of the month
string endDay = end.DayOfWeek.ToString(); //Last weekday of the month
var d = DateTime.Today;
// Start
d.AddDays(-d.Day+1);
// End
d.AddMonths(1).AddDays(-d.Day).Dump();
The first day is easy with the DateTime constructor. The last day is one day less than the first day of the next month.
public static void FirstAndLastDayOfMonth(DateTime date, out DateTime first, out DateTime last) {
first = new DateTime(date.Year, date.Month, 1);
DateTime nextFirst;
if (first.Month == 12) nextFirst = new DateTime(first.Year + 1, 1, 1);
else nextFirst = new DateTime(first.Year, first.Month + 1, 1);
last = nextFirst.AddDays(-1);
}
you can also get last day this way:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));
or:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
This link may also help you:
http://www.c-sharpcorner.com/UploadFile/scottlysle/FirstAndLastDay10262007135750PM/FirstAndLastDay.aspx
DateTime dt = DateTime.Now.AddDays(-(DateTime.Now.Day - 1));
int lday= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
DateTime DTY = new DateTime(DateTime.Now.Year, DateTime.Now.Month, lday);
MessageBox.Show("First Day :- "+dt.DayOfWeek.ToString());
MessageBox.Show("Last Day :-" + DTY.DayOfWeek.ToString());
To get first day of month:
String day = System.DateTime.Now.DayOfWeek.ToString();
int date = System.DateTime.Now.Day;
String fdm = System.DateTime.Now.AddDays(-Convert.ToDouble(date - 1)).DayOfWeek.ToString();
To get last day of month:
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);
string lastday = lastDay.DayOfWeek.ToString();
How do I covert JavaScript string "5:00 PM" to DateTime or TimeSpan when it get send to the MVC controller. I am using
bootstrap-timepicker
// usage
<script type="text/javascript">
$('#timepicker1').timepicker();
</script>
Javascript payload
{
Skip: 0
Status: []
Take: 15
DueTime: "1:00 PM" // keep in mind that this is a string
}
Server Object would be something like
class TimeSheet
{
public TimeSpan DueTime;
}
Use DateTime.Parse. Convert on server(on controller) when your string would transmit with your time.
http://msdn.microsoft.com/ru-ru/library/system.datetime.parse(v=vs.110).aspx
Okay so I read everyhting wrong hence the deleted answer.. !
But I'm not giving up ;)
Your bootstrap-timepicker, will give you a time as this "1:00 PM".
But before that we are going to look on the serverside to see what we can parse into a datetime object.
This is C# for parsing datetime.
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "15/08/2000 16:58"
format = "dd/MM/yyyy HH:mm"
result = DateTime.ParseExact(dateString, format, provider);
Now as you se your string wont look like that I'm going to assume that you want todays date!
This is function I tend to use most of the times when converting, to 24H clock.
function ConvertTimeformat(str) {
var time = str;
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
//Creating the todays date in the right format
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var todaysdate = dd+'/'+mm+'/'+yyyy +" " ; //<--I added an extra space!
var hoursNminutes = sHours + ":" + sMinutes
//CREATE THE RIGHT FORMAT FOR DATE.PARSEXACT "dd/MM/yyyy HH:mm"
var dateToParse = todaysdate + hoursNminutes
return dateToParse;
}
To Use the function do like this!
//Call it and provide your bootstrap time. And make it return to a variable
var dateToBeSentToServer = ConvertTimeformat("1:00 PM");
//OR With the bootstraptime as a variable
var dateToBeSentToServer = ConvertTimeformat(timevariable);
Now you can send dateToBeSentToServer to your serverside for parsing!
I have a textfield that has a date with the format "12/23/2010".Is there away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.
1.Get datetime 12/23/2010 and get number '23'
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21]
3.Insert the new datetime number [ie:12/21/2010 ]
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);
Is this possible?or should i be looking to another way.Ask the user to insert the data instead.
Try this :
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
if(DateTime.TryParse(myDate, out time);) {
Console.WriteLine(time.Month);
}
else {
//Not a valid date.
}
I need to create a midnight DateTime
I've just done this:
DateTime endTime = DateTime.Now;
endTime.Subtract(endTime.TimeOfDay);
Haven't test it yet, I'm assuming it works but is there a better/cleaner way?
Just use foo.Date, or DateTime.Today for today's date
DateTime endTime = DateTime.Now.Date;
Now endTime.TimeOfDay.ToString() returns "00:00:00"
DateTime.Now . AddDays(1) . Date
DateTime.Today
You can use DateTime.Today with exact seconds of the midnight.
DateTime today = DateTime.Today;
DateTime mid = today.AddDays(1).AddSeconds(-1);
Console.WriteLine(string.Format("Today: {0} , Mid Night: {1}", today.ToString(), mid.ToString()));
Console.ReadLine();
This should print :
Today: 11/24/2016 10:00:00 AM , Mid Night: 11/24/2016 11:59:59 PM
var dateMidnight = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMdd"), "yyyyMMdd", CultureInfo.InvariantCulture);
private bool IsServiceDatabaseProcessReadyToStart()
{
bool isGoodParms = true;
DateTime currentTime = DateTime.Now;
//24 Hour Clock
string[] timeSpan = currentTime.ToString("HH:mm:ss").Split(':');
//Default to Noon
int hr = 12;
int mn = 0;
int sc = 0;
if (!string.IsNullOrEmpty(timeSpan[0]))
{
hr = Convert.ToInt32(timeSpan[0]);
}
else
{
isGoodParms = false;
}
if (!string.IsNullOrEmpty(timeSpan[1]))
{
mn = Convert.ToInt32(timeSpan[1]);
}
else
{
isGoodParms = false;
}
if (!string.IsNullOrEmpty(timeSpan[2]))
{
sc = Convert.ToInt32(timeSpan[2]);
}
else
{
isGoodParms = false;
}
if (isGoodParms == true )
{
TimeSpan currentTimeSpan = new TimeSpan(hr, mn, sc);
TimeSpan minTimeSpan = new TimeSpan(0, 0, 0);
TimeSpan maxTimeSpan = new TimeSpan(0, 04, 59);
if (currentTimeSpan >= minTimeSpan && currentTimeSpan <= maxTimeSpan)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}