How Store datetime value in to local datetime variable? - c#

I am stored some value in to session. And retrieve some column datetime value with where clause and use this session value.
Code:
DateTime Currentdate = default(DateTime);
Session["d_id"] = dt.Rows[0]["d_id"];
Currentdate = objdl.GetScalerValue("select IsNull(Max(LoginDate),GETDATE()) from
q_logintrack_panel where Id= '" + Session["d_id"].ToString() + "'");
Here its produce error at 3rd row.
Error: string can not be explicitely convert into system.Datetime.
So please give me the exact solution please...

You need to parse string returned by GetScalarValue to a DateTime object:
DateTime Currentdate = default(DateTime);
Session["d_id"] = dt.Rows[0]["d_id"];
var dtStr = objdl.GetScalerValue("select IsNull(Max(LoginDate),GETDATE()) from q_logintrack_panel where Id= '" + Session["d_id"].ToString() + "'");
Currentdate = DateTime.Parse(dtStr);

Related

DateTime Comparison with IF statement not working

Am trying to make a comparison of DateTime in xamarin, but it has failed to work , below is my code:
When the system date is equal to the time set by users , it Toasts a
message
DateTime dt = DateTime.Now.ToLocalTime();
string timeset = "11:37".Trim();
DateTime oDate = DateTime.ParseExact(timeset, "HH:mm", null);
System.Diagnostics.Debug.WriteLine(" System Time : " + dt + " Set Time : " + oDate);
if (dt==oDate)
{
StartService();
}
What might be more helpful is to use the difference between the two times:
var diffInSeconds = (dt - oDate).TotalSeconds;
So:
DateTime dt = DateTime.Now.ToLocalTime();
string timeset = "08:56".Trim();
DateTime oDate = DateTime.ParseExact(timeset, "HH:mm", null);
System.Diagnostics.Debug.WriteLine(" System Time : " + dt + " Set Time : " + oDate);
var diffInSeconds = (dt - oDate).TotalSeconds;
System.Diagnostics.Debug.WriteLine(diffInSeconds);
if (Math.Abs(diffInSeconds) < 60)
{
System.Diagnostics.Debug.WriteLine("Equal");
}
This gives the difference to the nearest minute.
There are plenty of examples found via Google.

how to get only date part from date string in C#

i need to get in this format "2015-10-03" , but im getting like this "10/3/2015" and "10/3/2015 12:00:00 AM" both are not working in my query .because my updateddate datatype is date only
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
DateTime frmdt = Convert.ToDateTime(Fromdate);// 10/3/2015 12:00:00 AM
ToDate = Txtbox_AjaxCalTo.Text.Trim();
DateTime todt = Convert.ToDateTime(Fromdate);
i want query like this
updateddate between '2015-10-03' and '2015-10-03'
full query
gvOrders.DataSource = GetData(string.Format("select * from GoalsRoadMap where Activities='{0}' and project ='" + ProjectName + "' and updateddate between '2015-10-03' and '2015-10-03' ", customerId));
try this:
DateTime frmdt = Convert.ToDateTime(fromDate);
string frmdtString = frmdt.ToString("yyyy-MM-dd");
or at once:
string frmdt = Convert.ToDateTime(fromDate).ToString("yyyy-MM-dd");
So your code could look like this:
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
string frmdt = Convert.ToDateTime(Fromdate).ToString("yyyy-MM-dd");
ToDate = Txtbox_AjaxCalTo.Text.Trim();
string todt = Convert.ToDateTime(todt).ToString("yyyy-MM-dd");
gvOrders.DataSource = GetData(string.Format("select * from GoalsRoadMap where Activities='{0}' and project ='" + ProjectName + "' and updateddate between '{1}' and '{2}' ", customerId, frmdt, todt ));
As mentioned by Christos you can format DateTime to universal Date string (here are examples https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx). But right way to create queries is to use parameters. The following sample for SqlClient, but the idea is the same for other providers.
var cmd=new SqlCommand("UPDATE Table1 SET field1=#value WHERE dateField=#date");
cmd.Parameters.Add("#date",SqlDbType.Date).Value=myDateTime; //myDateTime is type of DateTime
...
And you have an error in SQL, BETWEEN '2015-10-03' AND '2015-10-03' will return nothing. Instead try this one dateField>='2015-10-03' AND dateField<='2015-10-03'
You could format your date string as you wish. Let that dt is your DateTime object with the value 10/3/2015 12:00:00 AM. Then you can get the string representation you want like below:
var formatted = dt.ToString("yyyy-MM-dd");
If your SQL date items stored as date and time, not just date, then your problem will be that for items between '2015-10-03' and '2015-10-03', it returns nothing.
So you just need to add one day to your toDate.Date that its Time is 12:00:00 AM.
Something like this:
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
string frmdt = Convert.ToDateTime(Fromdate).Date; // 10/3/2015 12:00:00 AM
//Or
//var frmdt = DateTime.Parse(Txtbox_AjaxCalFrom.Text).Date;
ToDate = Txtbox_AjaxCalTo.Text.Trim();
string todt = Convert.ToDateTime(todt).Date.AddDays(1);// 11/3/2015 12:00:00 AM
now if run your query like this, it may works:
var items = allYourSearchItems.Where(x => x.Date >= frmdt && x.Date < todt );
None of the above answer worked for me.
Sharing what worked:
string Text="22/11/2009";
DateTime date = DateTime.ParseExact(Text, "dd/MM/yyyy", null);
Console.WriteLine("update date => "+date.ToString("yyyy-MM-dd"));

Inserting multiple values between daterange into DB

i have a form which collects 2 dates (start date & end date) in the format mm/dd/yyyy
I want to collect these 2 dates from the form, and then create a list of all dates between these 2 days, then insert them into seperate rows in mt database. Here is my code:
if(IsPost){
var bookedFrom = Request.Form["dateFrom"];
var bookedTo = Request.Form["dateTo"];
DateTime dateF = Convert.ToDateTime(bookedFrom);
DateTime dateT = Convert.ToDateTime(bookedTo);
var dates = new List<DateTime>();
for (var dt = dateF; dt <= dateT; dt = dt.AddDays(1))
{
dates.Add(dt);
}
foreach(var dat in dates){
db.Execute("INSERT INTO Property_Availability (PropertyID, BookedDate, BookedNotes, BookedType) VALUES (#0, #1, #2, #3)", rPropertyId, dat, Request.Form["BookedNotes"], Request.Form["BookedType"]);
}
}
However, when i try and post my form, i get the following error:
String was not recognized as a valid DateTime.
DateTime dateF = Convert.ToDateTime(bookedFrom);
Any idea where i'm going wrong?
Thanks
Just my 2 cents in help you out, also consider using debug to know whether what values are passed / etc.
if(IsPost){
DateTime pFrom = new DateTime();
DateTime pTo = new DateTime();
var bookedFrom = Request.Form["dateFrom"];
var bookedTo = Request.Form["dateTo"];
if(DateTime.TryParse(bookedFrom, out pFrom) && DateTime.TryParse(bookedTo, out pTo))
{
DateTime dateF = pFrom;
DateTime dateT = pTo;
var dates = new List<DateTime>();
for (var dt = dateF; dt <= dateT; dt = dt.AddDays(1))
{
dates.Add(dt);
}
foreach(var dat in dates){
db.Execute("INSERT INTO Property_Availability (PropertyID, BookedDate, BookedNotes, BookedType) VALUES (#0, #1, #2, #3)", rPropertyId, dat, Request.Form["BookedNotes"], Request.Form["BookedType"]);
}
}
else
{
Response.Write("<script language=javascript>alert('Invalid date from : " + bookedFrom + " and date to : " + bookedTo + "');</script>");
}
}
Based on your exception, you have some problems with format of Request.Form["dateFrom"] value.
For example date in your default locale is supposed to be in format 'dd/mm/yyyy' or something like that.
So if you exactly know format of date in this parameter it's better to use something like that
DateTime dateF = DateTime.ParseExact(bookedFrom, "MM/dd/yyyy", CultureInfo.InvariantCulture);

c# mysql datetime to unix time

I have the following problem. The timeformat my database gives me back depends on the server settings.
So, if I do this query:
string query = "SELECT d.id, i.name, d.address, d.sensor, d.value, d.made, d.received, s.type, r.name AS room
FROM info AS i
RIGHT JOIN data AS d ON i.address = d.address AND i.sensor = d.sensor
LEFT JOIN sensor_types AS s ON i.type = s.id
LEFT JOIN room AS r ON i.room = r.id
WHERE i.address = '" + address + "'
&& i.sensor = '" + sensor + "'
&& DATE(d.received) BETWEEN '" + start + "' AND '" + end + "'";
On server 1 I get back for today 2013-12-23 2:29:14 and on server 2 I get back 23-12-2013 2:29:14.
In some cases I need the unixtime so I use this function for it, which works fine in case 1 but gives an error in case 2:
public string DateTimeToUnixTime(string text)
{
DateTime myDate = DateTime.ParseExact(text, "yyyy-MM-dd HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
TimeSpan span = (myDate - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return ((double)span.TotalSeconds).ToString();
}
What is the best way to fix this?
If you need to convert datetime to unix time.
You can use UNIX_TIMESTAMP() function of MySQL for that.
Try this:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Dec 23 2013 02:29AM', '%M %d %Y %h:%i%p'))
You can read more here.
Hope that helps! :)
Not saying it's the best way, but if the only possible formats are those two, you could test for one using DateTime.TryParseExact, and if it fails, assume it's the other format.
DateTime myDate;
if (!DateTime.TryParseExact(text, "yyyy-MM-dd HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.None, out myDate);
{
myDate = DateTime.ParseExact(text, "dd-MM-yyyy HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
}

SQL SELECT query not retrieving rows from a simple Access database

The DayDate column in the database is of type DateTime & I'm passing a string formulated using a DateTimePicker in a form. The reader.HasRows always returns false!! I don't know what I'm doing wrong. Any help would be appreciated. The code that I used is below.
if (!this.con.IsConnected())
{
this.con.Connect();
}
this.cmd = new OleDbCommand("SELECT DayNo FROM [Calendar] WHERE DayDate = " + date + "", this.con.conObj());
this.reader = cmd.ExecuteReader();
this.reader.Read();
int dayNo;
if (this.reader.HasRows)
{
dayNo = int.Parse(reader[0].ToString());
}
else
{
throw new InfoException("The system could not locate the date in the system");
}
The problem is your comparing a Date value to a DateTime so in essence you could possibly be comparing values like this:
DayDate = "2011-12-18 14:22:54"
Date = "2011-12-18 00:00:00"
You need to truncate the time part from your DB dates, try something like this:
"SELECT DayNo FROM [Calendar] WHERE dateadd(dd, 0, datediff(dd, 0, DayDate)) = " + date
Or if using SQL Server 2008 you can do:
"SELECT DayNo FROM [Calendar] WHERE cast(DayDate As Date) = " + date

Categories