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.
Related
I am trying to filter data between two dates; today 12:00 am to tonight at 12:00 pm. But I am getting this error:
System.Data.SqlClient.SqlException (0x80131904)) conversion data or time from character to string
Code:
DateTime today = DateTime.Today;
string fileNameBase = today.ToString("dd-MMM-yyyy 12:00:00 AM");
ExportToExcel export = new ExportToExcel();
export.ExportTable("SELECT daytime, COLUMN_1, COLUMN_2, COLUMN_3, COLUMN_4, BSNO, Spare1, COLUMN_5, COLUMN_6, Spare2, DEG, TEMP3, Spare3, CAS1, CAS2, ACTIVA, Spare4, CAS3, CAS4, PHOS, Spare5, Spare6, Spare7, TEMP2, CAS5, CAS6, DRY, TEMP1 FROM TABLE_2 WHERE daytime BETWEEN '" + (today.ToString("dd-MMM-yyyy 12:00:00 AM")) + "' AND '" + today.ToString("dd-MMM-yyyy 12:00:00 PM") + "' ");
export.SaveWorkbook();
export.shutDown();
You can do this:
DateTime today = DateTime.Today;
string dateAMFormat = today.ToString("dd-MMM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture));
string datePMFormat = today.AddHours(12).ToString("dd-MMM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture));
ExportToExcel export = new ExportToExcel();
export.ExportTable("SELECT daytime, COLUMN_1, COLUMN_2, COLUMN_3, COLUMN_4, BSNO, Spare1, COLUMN_5, COLUMN_6, Spare2, DEG, TEMP3, Spare3, CAS1, CAS2, ACTIVA, Spare4, CAS3, CAS4, PHOS, Spare5, Spare6, Spare7, TEMP2, CAS5, CAS6, DRY, TEMP1 FROM TABLE_2 WHERE daytime BETWEEN '" + dateAMFormat + "' AND '" + datePMFormat + "' ");
export.SaveWorkbook();
export.shutDown();
More on this here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#tSpecifier
How do I get the AM/PM value from a DateTime?
I know this is an old problem but I cannot figure out why.
I have 2 voids binding in 2 buttons GENERATE and SAVE:
private void btn_generate_Click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(textstarteddate.Text);
DateTime enddate = new DateTime (startdate.Year, 12, 31);
Int64 addedDays = Convert.ToInt64(textdaycount.Text);
string taskID = texttaskID.Text;
string machine = cb_machineID.Text.Trim();
string note = texttasknote.Text;
string runningtime = RMT.Text;
string period = cb_periodID.Text.Trim();
_dtdate.Columns.Add(new DataColumn("Maintenance Date", typeof(DateTime)));
_dtdate.Columns.Add(new DataColumn("TaskID", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Machine", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Note", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Period", typeof(String)));
_dtdate.Columns.Add(new DataColumn("Running Time", typeof(String)));
_dtdate.Rows.Clear();
G1.DataBindings.Clear();
if (cb_typescheID.Text == "Fix Date")
{
do
{
_dtdate.Rows.Add(startdate.Date, taskID, machine, note, period);
startdate = startdate.AddDays(addedDays);
G1.Refresh();
//DateTime end = startdate;
}
while (startdate <= enddate);
}
G1.DataSource = _dtdate;
G1.Columns["Maintenance Date"].DefaultCellStyle.Format = "d";
}
and
private void btn_save_Click(object sender, EventArgs e)
{
if (cb_typescheID.Text == "Fix Date")
{
foreach (DataRow dr in _dtdate.Rows)
{
sqlstr = sqlstr + " INSERT INTO [PerformTask] (Year, Date, TasKID, MachineID, PerformStatus, ScheduleID, PeriodID) Values ('" + startdate.Year + "', '" + dr["Maintenance Date"].ToString() + "',";
sqlstr = sqlstr + "'" + texttaskID.Text.Trim() + "', '" + machine + "', 'RS_Open', '" + typeschedule + "', '" + period + "')";
G1.Columns["Maintenance Date"].DefaultCellStyle.Format = "d";
}
}
}
I tried every way to convert it to only Date (dd/MM/yyyy) but it still display on a DataGridView(G1) but when i try to save it into my datatable in SQL, its format is still "dd/MM/yyyy hh:mm:ss tt" no matter how i convert it. I have read to old topic about this problem, tried their ways but still cannot save the data the way I want.
Please help. Thank you.
You could add the Column as string:
_dtdate.Columns.Add(new DataColumn("Maintenance Date", typeof(String)));
and then format the date when adding a new row:
_dtdate.Rows.Add(startdate.Date.ToString("dd/MM/yyyy"), taskID, machine, note, period);
If I understand you correctly, your problem is not displaying the date in date format within the grid, but has to do with the format in SQL?
Is your database field date or datetime (assuming we are MS SQL Server)? If you do not need the time information, it is much better to change the field to date. It is much to be preferred to store dates as dates rather than as strings, since you can perform operations on them as dates, without having to cast. In general, you should never be concerned with the way your database formats values; it is up to your presentation layer to handle formatting; your database should just concern itself with the efficient storing of data, and not worry about how that data looks.
I wanted to display all rows and columns in my DB between specific dates on an aspx web. However, dates are not recorded in date or date time format. And it seems it is not possible to convert them to date format. I try to do this like this;
public DataTable DisplayRecord()
{
var reqID = Request.QueryString["MyId"].ToString();
//Date parsing
String[] ids = reqID.Split('-');
String date1 = ids[0];
String date2 = ids[1];
String provider = ids[2];
SqlDataAdapter Adp = new SqlDataAdapter("SELECT * FROM flightLogs WHERE depDate_depTime=CONVERT(date,depDate_depTime,104) AND depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104)", connection);
/*SqlDataAdapter Adp = new SqlDataAdapter("SELECT F.PNR, C.amount, F.provider, F.depDate_depTime FROM flightLogs F INNER JOIN companyLogs C ON F.PNR = C.PNR"+
" WHERE F.depDate_depTime=CONVERT(date,F.depDate_depTime,104) AND F.depDate_depTime BETWEEN CONVERT(date,'" + date1 + "',104)" +
" AND CONVERT(date,'" + date2 + "',104) AND F.provider='" + provider + "' ORDER BY F.depDate_depTime ASC", connection);*/
DataTable Dt = new DataTable();
Adp.Fill(Dt);
FlightMonitor.DataSource = Dt;
FlightMonitor.DataBind();
return Dt;
}
But i get this error;
"Conversion failed when converting date and/or time from character string."
Also data in my DB is shown like this;
origin destination deptDate_depTime PNR flightno provider
KBP AMS 18.09.2015 - 17:35:00 5RQZ43 PS712 Amadeus
ATH FRA 10.07.2015 - 12:30:00 ZFY8XW PS716 PGS
it is a bad idea to store datetime values in varchar columns as you can see.
if you need a specific format, then you should convert it while you are about to display that value to the users.
but to make things working for now, you can change your where clause from this:
depDate_depTime=CONVERT(date,depDate_depTime,104)
to this:
depDate_depTime = convert(datetime, left(depDate_depTime, 10) + ' ' + right(depDate_depTime, 8), 104)
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);
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);
}