I want to count total time in hh:mm:ss format. and I have minutes in int like (465).
I made:
CONVERT(varchar, CONVERT(datetime, cast(cast(TotalMin/60 as int) as nvarchar(50)) + ' : ' + cast(TotalMin%60 as nvarchar(50))),108) AS TotalMin
but it shows below error. Not in SQL Server but when I run code in c#:
Conversion failed when converting date and/or time from character
string.
You can use this code to get the string in SQL Server. It will convert hours and minutes and add 00 for seconds as you don't have them (you're using integer value for minutes):
declare #min int = 465
select right('0' + cast(#min/60 as varchar(2)),2)
+ ':'
+ right('0' + cast((#min - (#min/60)*60) as varchar(2)),2)
+ ':00'
It will work for up to 5999 minutes (99 hours and 59 minutes).
If you need a Unicode version:
declare #min int = 465
select right(N'0' + cast(#min/60 as nvarchar(2)),2)
+ N':'
+ right(N'0' + cast((#min - (#min/60)*60) as nvarchar(2)),2)
+ N':00'
Try this:
TimeSpan t = TimeSpan.FromMinutes( TotalMin);
and see this for more
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
This will help you
You want to multiply out to milliseconds as the fractional part is discarded.
SELECT DATEADD(ms, 121.25 * 1000, 0)
If you want it without the date portion you can use CONVERT, with style 114
SELECT CONVERT(VARCHAR, DATEADD(ms, 121.25 * 1000, 0), 114)
Related
I am trying to select items from a database where their date equals the date in the Session. It says there is no row at position [0][2], but there is actually a row there. This is my code:
DateTime b = Convert.ToDateTime(Session["Dat"]);
int D = b.Day;
int M = b.Month;
int Y = b.Year;
string dat = M + "/" + D + "/" + Y ;
DataTable m;
m = DAL.SelectFromTable(
"SELECT * FROM [ToDoList] where [UserID]='" + k + "' and [D]="+ dat);
if (m.Rows.Count > 0)
{
Response.Write("</br></br></br><center>" + m.Rows[0][2].ToString() + "</center>");
}
Access requires dates to be surrounded by #.
Assuming DAL is not written by you, and you don't really have the option to correctly and securely query the database, you would have to do something like:
...and [D] = #" + dat + "#"
However, #thisextendsthat has good point that this will probably return no results because you would have to have the time portion of the date exactly as the data is in the database and you are only using month, day and year to build the date.
You could also get around the time portion by selecting a range:
... and [D] BETWEEN #" + dat + "# AND #" + // one day greater than your date at midnight + "#"
But if you do that you have to be careful not to create an impossible date like May 32, for instance.
Be sure to thank your teacher for continuing to train students to code insecurely, keeping SQL injection vulnerabilities right at the top of the OWASP top 10, right where it belongs.
There is no reason to reinvent the wheel, just use method ToString:
DateTime b = Convert.ToDateTime(Session["Dat"]);
DataTable m;
m = DAL.SelectFromTable("select * from [ToDoList] where [UserID] = '" + k + "' and [D] = #" + dat.ToString("yyyy'/'MM'/'dd") + "#");
As Crowcoder says, which DB are you using? That will help determine how you ought to be sending dates into your queries.
If the underlying field is a datetime then you may need to explicitly trim the time part from the value in order to compare to a date. In Sql server:
...where CAST([D] as DATE) = [The date passed in from from C#]
Otherwise you might be comparing today at some arbitrary time to today at midnight, which won't give you what you want.
Also, please think think about paramterising your Sql queries - building up a string literal like this is bad practice and leaves your app vulnerable to Sql injection attacks.
I am trying to get my values sorted ascending but although I get the results, it is not sorted properly as seen below:
"50","2016-12-1","2016-12-01 17:42:30","2016-12-01 17:42:30","0","0"
"50","2016-12-10","2016-12-10 07:31:43","2016-12-10 07:31:43","0","0"
"50","2016-12-11","2016-12-11 04:27:35","2016-12-11 04:27:35","0","0"
"50","2016-12-12","2016-12-12 07:52:18","2016-12-12 18:02:47","10","10"
"50","2016-12-13","2016-12-13 07:28:22","2016-12-13 18:18:31","10","50"
"50","2016-12-14","2016-12-14 07:32:34","2016-12-14 18:37:09","11","4"
"50","2016-12-15","2016-12-15 07:14:15","2016-12-15 07:14:15","0","0"
"50","2016-12-2","2016-12-02 07:23:33","2016-12-02 17:37:22","10","13"
"50","2016-12-3","2016-12-03 07:49:27","2016-12-03 17:45:01","9","55"
"50","2016-12-5","2016-12-05 07:40:22","2016-12-05 17:32:29","9","52"
"50","2016-12-6","2016-12-06 07:41:43","2016-12-06 17:42:00","10","0"
"50","2016-12-7","2016-12-07 07:20:33","2016-12-07 17:40:51","10","20"
"50","2016-12-8","2016-12-08 07:22:02","2016-12-08 20:56:37","13","34"
"50","2016-12-9","2016-12-09 07:35:06","2016-12-09 18:11:18","10","36"
The 2016-12-2 is below the 2016-12-15. This is how I get this values:
SELECT uid, scan_date as 'Date' , min(scan_time) as 'Time In', max(scan_time) as 'Time
CAST(((strftime('%s', max(scan_time)) - strftime('%s', min(scan_time))) % (60 * 60 * 24)) / (60 * 60) AS TEXT) as Hours,
CAST((((strftime('%s', max(scan_time)) - strftime('%s', min(scan_time))) % (60 * 60 * 24)) % (60 * 60)) / 60 AS TEXT) as Minutes
FROM tbl_scanTimes
GROUP BY uid, scan_date
ORDER BY uid asc, scan_date
This is how I insert data into the sqlite
var sCommand = new StringBuilder(#"REPLACE INTO tbl_scanTimes(branch, uid, scan_date, scan_time) VALUES ");
sCommand.Append(string.Join(",", (from DataRow row in values.Rows
let branch = _yard
let empId = row[0].ToString().Trim()
let scanTime = row[1].ToString().Trim()
let date = Convert.ToDateTime(scanTime)
let oDate = date.Year+"-"+date.Month+"-"+date.Day
select string.Format("('{0}','{1}','{2}','{3}')", branch, empId, oDate, scanTime)).ToArray()));
sCommand.Append(";");
Is there a way that I can put 0 in the day part of 2016-12-1 so that it will be 2016-12-01? Thank you.
Following CL's comment on supported date formats, I think that your data-inserting may be using your desktop dateformat settings, because you are passing oDate as just '{2}' in the format string.
Try using this format when you insert data:
string.Format("('{0}','{1}','{2}','{3}')",
branch, empId, oDate.ToString("yyyy-MM-dd HH:mm:ss.fff"), scanTime)
(yes, I know that it can be packed into {2} expr, I just want it to stand out).
Btw. watch out for the upper-case MM and HH. It's important.
Here's the full list
Whever it works or not, check carefully what's the actual query you are sending to the db. Place a breakpoint on that line and see what the Format() method produces.
I have this simple query
insert into my_table(date) values(getdate())
The result is 2017-01-05 12:41:37.273.
I want when I do
select *
from my_table
from my Windows Forms application to set the label1.text = 5 Thu 12:41
2017-01-05 12:41:37.273 ----> 5 Thu 12:41
How can I achieve that with C# code ?
Assuming that you read the data from SQL Server into your C# application I'm pretty sure, that a column of sql type DATETIME will be mapped to a C# type DateTime.
What you need is the textual format of this:
DateTime d = DateTime.Now;
MessageBox.Show(d.ToString("d ddd HH:mm"));
You can parse string to DateTime and wrtie your own format.
DateTime myDateTime = DateTime.Parse("2017-01-05 12:41:37");
string formatedDateTime = myDateTime.ToString("dd-mm-yyyy");
From SQL you can you the below format to get your expected result:
SELECT CAST(DATEPART(D, GETDATE()) AS VARCHAR(2)) + ' ' +
LEFT(DATENAME(WEEKDAY, GETDATE()), 3) + ' ' +
LEFT(CONVERT(VARCHAR(8), GETDATE(), 108), 5)
-- Output: 5 Thu 05:22
I have sql query where i am converting minutes to HH:MM format by using this query
declare #tempt table(col1 int)
insert into #tempt
select 140
union all
select 35
select cast (cast((col1)/60 as varchar)
+ ':' + RIGHT('0' + cast((col1)%60 as varchar),2) as Time) Running
from #tempt
and output is
Running
02:20:00.0000000
00:35:00.0000000
But i want to show as 02:20 and 00:35 .
How do i eliminate these rest of zero's ?
We can cast it like this,
SELECT CONVERT(VARCHAR(5),getdate(),108)
replace getdate() with your datetime object
This will give you the result in Time datatype, in hh:mm:ss format
declare #tempt table(col1 int)
insert into #tempt
select 140
union all
select 35
select cast (cast((col1)/60 as varchar)
+ ':' + RIGHT('0' + cast((col1)%60 as varchar),2) as Time(0)) Running
from #tempt
The problem is that the dates are stored in the SQL database as nvarchar() and the times are stored in a separate column. I only have read access to this database, so I can't change the format. Besides, it would probably void our support if the manufacturer found out.
As I see I need to first combine the dates and times into one cell as a datetime and then subtract the previous row from the current.
ActualTime, ActualDate
5:30:26, 31-Dec-09
16:01:47, 31-Dec-09
17:35:50, 31-Dec-09
18:31:31, 31-Dec-09
18:51:03, 31-Dec-09
18:55:35, 31-Dec-09
19:26:53, 31-Dec-09
5:25:37, 1-Jan-10
5:38:36, 1-Jan-10
5:46:58, 1-Jan-10
6:27:00, 1-Jan-10
Several people have asked what language I was using. I was hoping to do all of this at the server. On the code side (C#) it's a trivial problem.
Like I said I am looking for an SQL Server server-side solution.
In Microsoft SQL Server, to convert your columns in a date you can
Select Cast( ActualDate + ' ' + ActualTime AS DateTime)
to compare between two dates
Select
Datediff(
second,
Cast('13-dec-2009 ' + '19:39:33' As DateTime),
Cast('13-dec-2009 ' + '19:26:33' As DateTime)
)
More on DATEDIFF (Transact-SQL) parameters.
And to get the difference from the current date/time use the GETDATE(),
Select
*,
oldness = DateDiff(
second,
GETDATE(),
Cast(ActualDate + ' ' + ActualTime AS DateTime)
)
From
your_table
Finally to do it between rows (for the whole table..),
Select *,
Cast(ActualDate + ' ' + ActualTime AS DateTime) as [fulldate],
DiffFromPrevious = Coalesce(
DateDiff(
second,
(
Select Top 1 Cast(ActualDate + ' ' + ActualTime AS DateTime) AS [fulldate]
From yourtable
Where Cast(ActualDate + ' ' + ActualTime AS DateTime) < Cast(t1.ActualDate + ' ' + t1.ActualTime AS DateTime)
Order By [fulldate] Desc
),
Cast(ActualDate + ' ' + ActualTime AS DateTime)
),
0)
From
yourtable t1
Order By
[fulldate] Asc
What language are you using, and what kind of Database is it? I'm not sure if the database has capabilities to do row manipulation within a query (subtracting one row from the other), so you would have to do this programmatically. I'm not sure what language you're using, but if it has a Date or Time API then you can use that to create a Date object. There should a function that returns the total number of seconds since a starting date (January 1, 1970 or something). You create your two Date objects, convert into number of seconds and then subtract them. You can then calculate the number of days between them.
If you're using PHP, I suggest you use the strtotime() function to convert it into a time object. Do this for both dates. The difference will give you the number of seconds between them.