How to check if for example 30 min have passed? - c#

i have the following Code:
if (v != null && DateTime.Now > v.Besetzt_Von)
{
Debug.WriteLine("Hallo, das ist die Ausgabe! : " + v.Thema + v.Besetzt_Von + v.Besetzt_Bis);
string clientId = GetClientId(req);
DateTime TimeCheck = v.Besetzt_Von;
if (TimeCheck.AddMinutes(30) > v.Besetzt_Von)
{
String hql = "UPDATE Buchung as b " +
"set STORNO = :Storno " +
"where ID IN (SELECT rr.Buchung FROM Raumreservierung rr " +
"where BESETZT_VON = :Von and Raum IN (SELECT r.ID FROM Raum r " +
"join r.Panel pl where pl.ID = :PanelId))";
IQuery query = CurrentSession.CreateQuery(hql);
query.SetParameter("Storno", DateTime.Now);
query.SetParameter("Von", v.Besetzt_Von);
query.SetParameter("PanelId", clientId);
int result = query.ExecuteUpdate();
Debug.WriteLine("Rows affected: " + result);
}
}
I want that if for example Besetzt_Von = 14:00 o'clock, the Query only gets executed if 30 minutes have passed (14:30). I did that with the if clause, but it does not work. The Query is always executing. What iam doing wrong?

change
if (TimeCheck.AddMinutes(30) > v.Besetzt_Von)
which doesn't do anything (this means if v.Besetz_von < v.BesetzVon + 30 minutes, which is of course always true)
to
if (DateTime.Now > v.Besezt_Von.AddMinutes(30))

// DateTime TimeCheck = v.Besetzt_Von; <-- you don't need this
if (DateTime.Now > v.Besetzt_Von.AddMinutes(30))
{
// ...
}

Related

Date is not getting properly bound in my textbox Jquery

I want to show my date field in a textbox which is coming from Oracle database.
The scenario is, my date stored in DB column is 01-12-17 and its datatype is date.
and while binding it is coming as 1-11-17 I don't know why it's happening like this.
Here is my binding code.
if (getJSONValue.LAUNCH_DATE != "" || getJSONValue.LAUNCH_DATE != null) {
var newDate = new Date(getJSONValue.LAUNCH_DATE);
var day = newDate.getDate();
var month = newDate.getUTCMonth() + 1;
var year = newDate.getFullYear();
$('#txtLaunchDate').val(day + "-" + ((month)) + "-" + year.toString().substr(-2));
}
else {
$('#txtLaunchDate').val("");
}
When you call this :
var newDate = new Date(getJSONValue.LAUNCH_DATE);// if your date is 01-12-2017
the result is : Thu Jan 12 2017 00:00:00
It switches month and day info.
And as you try to add two values it contatenates :
var month = newDate.getUTCMonth() + 1; //returns 1 + 1 as string and the result is 11.
That that is why you see 1-11-17.
If you want a simple solution,
var str = getJSONValue.LAUNCH_DATE; //"01-12-2017";
var array = str.split("-");
var day = array[0];
var month = array[1];
var year = array[2].substr(2);
var dateStr = day + "-" + month + "-" + year;
Use getMonth instead of getUTCMonth:
var newDate = new Date('2017-12-01T00:00:00');
var day = newDate.getDate();
var month = newDate.getMonth()+1;
var year = newDate.getFullYear();
alert(day + "-" + ((month)) + "-" + year.toString().substr(-2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this
var month = (Number(newDate.getUTCMonth()) + 1);

How can i subtract one hh.mm format time(which is decimal) from another?

I have 4 records in an SQL database. Which has 2 colums hours1 and hours2
Record1 : hours1- 1.00,hours2- 1.00
Record2 : hours1- 9.00,hours2- 5.30
Record3 : hours1- 9.00,hours2- 9.00
Record4 : hours1- 3.00,hours2- 3.00
So here I got the sum of these colums as :
SUM of column1 : 22.00
SUM of column1 : 18.30
These are decimal but I consider it as time.
Now I want to subtract column2 sum from column1 sum i.e.
22.00 - 18.30
So I will get 3.7 which is wrong because I considered as a time.
I want final answer as : 3.30 (justification for requirement : so when I add this result to 18.30 (18.30+3.30 which is 21.60 = 22.00 hours as 60 minute = 1 hour) I got total 22.00).
Can anyone help me how to get 3.30 as result? I cant use TimeFormat.
As everyone said in the comments: conversion is needed, and it must be done before summing takes place.
Here is how:
var times1 = new decimal[] { 1.00m, 9.00m, 9.00m, 3.00m };
var times2 = new decimal[] { 1.00m, 5.30m, 9.00m, 3.00m };
var hours1 = ActualHours(times1).Sum(); // using System.Linq;
var hours2 = ActualHours(times2).Sum();
var diff = hours1 - hours2;
var result = "Actual: hours1 = " + hours1 +
", hours2 = " + hours2 +
", diff = " + diff + "\r\n" +
"Printed: hours1 = " + Print(hours1) +
", hours2 = " + Print(hours2) +
", diff = " + Print(diff);
Methods used:
public IEnumerable<decimal> ActualHours(params decimal[] values)
{
foreach (var v in values)
{
var t = Math.Truncate(v);
yield return t + (v - t) / 0.6m;
}
}
public string Print(decimal v)
{
var t = Math.Truncate(v);
return (t + (v - t) * 0.6m).ToString("0.00");
}
Output:
Actual: hours1 = 22.0, hours2 = 18.5, diff = 3.5
Printed: hours1 = 22.00, hours2 = 18.30, diff = 3.30

InvalidArgument=Value of '1' is not valid for 'index'

I have an error in my C# application that interacts with MDB access DB.
The error is:
InvalidArgument=Value of '1' is not valid for 'index'.
My code:
objConn.Open();
listView1.Items.Clear();
OleDbCommand cmd = new OleDbCommand("select a.bill_Id,a.bill_Number,a.bill_Date,c.sup_Name,Sum(b.de_NetPrice),a.bill_Note from (suppliers c right JOIN bills a on c.sup_Id = a.bill_From) LEFT JOIN bill_Details b on a.bill_Id = b.bill_Id where a.bill_Id like '%" + txbSearch.Text + "%' or a.bill_Number like '%" + txbSearch.Text + "%' or c.sup_Name like '%" + txbSearch.Text + "%' or a.bill_Note like '%" + txbSearch.Text + "%' group by a.bill_Id,a.bill_Number,a.bill_Date,c.sup_Name,a.bill_Note order by a.bill_Date desc", objConn);
OleDbDataReader dataReader = cmd.ExecuteReader();
int i = 0;
while (dataReader.Read())
{
DateTime dt0 = DateTime.Parse(dataReader.GetValue(2).ToString());
int Date1 = DateTime.Compare(DateTime.Parse(dt0.ToShortDateString()), DateTime.Parse(txbFrom.Value.ToShortDateString()));
int Date2 = DateTime.Compare(DateTime.Parse(dt0.ToShortDateString()), DateTime.Parse(txbTo.Value.ToShortDateString()));
if (Date1 >= 0 && Date2 <= 0)
{
listView1.Items.Add(dataReader.GetValue(0).ToString());
// The error happens on the following line
listView1.Items[i].SubItems.Add(dataReader.GetValue(1).ToString());
listView1.Items[i].SubItems.Add(dt0.ToShortDateString());
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(3) ? "0" : dataReader.GetString(3));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(4) ? "0" : dataReader.GetDouble(4).ToString("n2"));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(5) ? "-" : dataReader.GetString(5));
}
i++;
}
objConn.Close();
The listview has these columns:
ID -- Number -- BillDate -- Supplier -- total -- Note
I may have found the issue.
If first time around the 'if (Date1 >= 0 && Date2 <= 0)' statemant evaluates to false, the i index will still get incremented. And then on the second iteration the if statement might evaluate to true, and then your index will be off-by-one, as there is just one Item in the ListView, but you try to get at using listView1.Items[1], instead of listView1.Items[0], which would be correct.
Solution would be to change the code to:
if (Date1 >= 0 && Date2 <= 0)
{
listView1.Items.Add(dataReader.GetValue(0).ToString());
listView1.Items[i].SubItems.Add(dataReader.GetValue(1).ToString());// The error appears on this line
listView1.Items[i].SubItems.Add(dt0.ToShortDateString());
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(3) ? "0" : dataReader.GetString(3));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(4) ? "0" : dataReader.GetDouble(4).ToString("n2"));
listView1.Items[i].SubItems.Add(dataReader.IsDBNull(5) ? "-" : dataReader.GetString(5));
i++;
}

Display Current Date and Time

I have to display the current date and time in the Master layout of my views.
I 've added the current date and time
<div class="date-time">#{
#Html.Label(string.Format("{0:F}",System.DateTime.Now))
}
</div>
The problem is need to update the time in real time.
It's not updating until I refresh the page.
Here is my java script code
function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
var currentDay = currentTime.getDay();
var currentMonth = currentTime.getMonth();
// Pad the minutes and seconds with leading zeros, if required
currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
// Choose either "AM" or "PM" as appropriate
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
// Convert the hours component to 12-hour format if needed
currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
// Convert an hours component of "0" to "12"
currentHours = (currentHours == 0) ? 12 : currentHours;
// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
return currentTimeString;
}
And the Layout file... Need to add the reference of the javascript file and I have added the bundle.
#Scripts.Render("~/bundles/clock")
<script>
function DiplayClock() {
var currentTime = updateClock();
document.getElementById("clock").firstChild.nodeValue = currentTime;
}
</script>
</head>
<body onload="DiplayClock(); setInterval('DiplayClock()', 1000);">
<div class="date-time">
<span id="clock"> </span>
</div>
</body>
A easy way to do it is:
'document.getElementById("date").innerHTML = new Date().toDateString()'
You have to use javascript.
First declare a timer at the beginning of your .js file:
var objTimer;
after that, you have to set the timeout interval in any initial .js function:
objTimer = setTimeout("DisplayDate()", 1000);
and then, of course, code the DisplayDate() function; something like:
function DisplayDate() {
var objDate = new Date;
var intDate = objDate.getDate();
var intDay = objDate.getDay();
var intMonth = objDate.getMonth();
var intYear = objDate.getYear();
var intHours = objDate.getHours();
var intMinutes = objDate.getMinutes();
var intSeconds = objDate.getSeconds()
var strTimeValue = "" + intHours
strTimeValue += ((intMinutes < 10) ? ":0" : ":") + intMinutes
strTimeValue += ((intSeconds < 10) ? ":0" : ":") + intSeconds
var strDate = intMonth + " " + intDate + ", " + intYear + " " + strTimeValue;
document.getElementById('fcr_spanDateTime').innerHTML = strDate;
}
Hope it helps.

How to get 30 days from today including the month january

My sql table contains date of birth of many people.dates are in mm/dd/yyyy format. I want select the persons details whose birth day in next 30days. And i use the following query for that,
SELECT Mem_FirstNA, Mem_LastNA, Mem_DOB FROM MemberDetails WHERE
ltrim(str(year(GETDATE()))) + -' + ltrim(str(month(Mem_DOB))) + '-' +
ltrim(str(day(Mem_DOB))) >= getdate() - 1 AND
ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' +
ltrim(str(day(Mem_DOB))) <= getdate() + 30
And full code is
public List<MemberData> GetThisMonthBirthday()
{
List<MemberData> MD = new List<MemberData>();
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Mem_FirstNA, Mem_LastNA, Mem_DOB FROM MemberDetails WHERE ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) >= getdate() - 1 AND ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) <= getdate() + 30", con))
{
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MemberData mb = new MemberData();
mb.Mem_NA = (string)reader["Mem_FirstNA"];
mb.Mem_LastNA =(string)reader["Mem_LastNA"];
mb.Mem_DOB = (Convert.ToDateTime(reader["Mem_DOB"]));
MD.Add(mb);
}
}
catch (Exception e) { throw e; }
finally { if (con.State == System.Data.ConnectionState.Open) con.Close(); }
return MD;
}
}
The problem is that this check only till December 31, if the persons birthday in 01/01/1987 , the query is not selected that details. Please help me to solve this problem. Thank you
There are lots of ways to do this, you need conditional logic depending on whether or not you are within 30 days of the end of the year. If you're using SQL Server, I'd wrap the logic in a function to make it more readable, e.g.:
CREATE FUNCTION [dbo].[IsBirthdayInRange]
(
#Birthday DATETIME,
#StartDate DATETIME,
#EndDate DATETIME
)
RETURNS BIT
AS
BEGIN
DECLARE #StartMonthDay INT
DECLARE #EndMonthDay INT
DECLARE #BirthdayMonthDay INT
SET #StartMonthDay = MONTH(#StartDate) * 100 + DAY(#StartDate)
SET #EndMonthDay = MONTH(#EndDate) * 100 + DAY(#EndDate)
SET #BirthdayMonthDay = MONTH(#Birthday) * 100 + DAY(#Birthday)
IF YEAR(#StartDate) <> YEAR(#EndDate)
BEGIN
IF #BirthdayMonthDay >= #StartMonthDay OR #BirthdayMonthDay <= #EndMonthDay
BEGIN
RETURN 1
END
END
ELSE
BEGIN
IF #BirthdayMonthDay >= #StartMonthDay AND #BirthdayMonthDay <= #EndMonthDay
BEGIN
RETURN 1
END
END
RETURN 0
END
You can then use it as:
...
WHERE IsBirthdayInRange(Mem_DOB, GETDATE(), GETDATE() + 30)

Categories