Working with Time Zones in SSRS - datetime

We store all our dates SQL Server 2008 database in UTC time in DateTime columns.
I'm using SSRS to create reports and I need to convert all the times on the reports to the Time Zone of the computer where they're running the report from.
I know could always just pass in the current timezone offset as a parameter to the report and add or subtract the offset from the timezone, but this wouldn't correctly show historical dates because of daylight savings.
Does SSRS have any functions that handle this? Should I pass the timezone to the SQL server functions and have the SQL Server convert the time?

I figured it out.
In the SSRS report, I've added a reference to the assembly System.Core
Then anywhere I needed to convert the timezone I used:
=Code.FromUTC(Fields!UTCDateFromDatabase.Value, Parameters!TimeZone.Value)
where Parameters!TimeZone.Value is the string value of the timezone which can be retrieved in the application by using TimeZone.CurrentTimeZone.StandardName
I should probably put what FromUTC does:
Shared Function FromUTC(ByVal d As Date, ByVal tz As String) As Date
Return (TimeZoneInfo.ConvertTimeBySystemTimeZoneId(d, TimeZoneInfo.Utc.Id, tz))
end function

Try using this instead:
=System.TimeZone.CurrentTimeZone.ToLocalTime(Fields!DateTime.Value)
For SSRS reports called from AX 2012, this is what I use.
Credit goes to this post: http://social.msdn.microsoft.com/Forums/en-US/500448a3-bf58-44ab-8572-81becd67d8b8/convert-utc-time-to-local-time?forum=sqlreportingservices

Related

Convert UTC Time Stamp to Date and Time in U-SQL

I'm fairly new to U-SQL so this may be a simple question.
I have a field, [utc_timestamp], in an ADL table with a unix time stamp in the form "1497178877" which measures the number of seconds from 1970-01-01.
Is there any easy way to convert this time stamp in U-SQL to both a date in the form of "2017-06-11" and a date time object?
My initial attempt didn't seem to work quite right.
#table =
SELECT * FROM
( VALUES
(1497178877)
) AS T(seconds);
DECLARE #dateStart = new DateTime(1970, 01, 01);
#result =
SELECT #dateStart.AddSeconds(seconds).ToString("yyyy-MM-dd") AS newDateString,
#dateStart.AddSeconds(seconds) AS newDate
FROM #table;
OUTPUT #result
TO "/Temp/Dates/Example1.txt"
USING Outputters.Tsv();
U-SQL is using C# for the expression language, so you can use C#/.NET to do it.
Here is a link answering how to do it in C#: How can I convert a Unix timestamp to DateTime and vice versa?
Since we are currently on .NET Runtime 4.5.2, you will not be able to use the 4.6 built-in method (we plan to upgrade to a newer version of the runtime, but I do not have an ETA yet).
If you want to avoid writing the transformation inline as a C# expression you can either deploy it via VS's code behind, with a U-SQL Func variable or create and register an assembly containing the UDF.

SQL find local date and time

I am facing the date and time issue in my sql server 2012 and web form. it is taking the server date and time. how i can get client location date and time. what i have done so far is.
Declare #TodayDate datetime
Set #TodayDate = (SELECT DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), GETDATE()))
it is giving me correct date only but not time. how to get both date and time.
In my webform i try this code, i got it from one forum again. Until now am not try it. Please help me to find correct solution for this.
DateTime convertedDate = DateTime.UtcNow;
DateTime localDate = convertedDate.ToLocalTime();
Actually it is not possible from server to locate user place. DateTime.Now show you server data not users date. You have to get user time through javascript. You can store utc time in Database. After that convert utc time to user time through javascript.

Issue with date when migrating databases between SQL Server 2008 and 2012 [duplicate]

I have the following piece of inline SQL that I run from a C# windows service:
UPDATE table_name SET
status_cd = '2',
sdate = CAST('03/28/2011 18:03:40' AS DATETIME),
bat_id = '33acff9b-e2b4-410e-baaf-417656e3c255',
cnt = 1,
attempt_date = CAST('03/28/2011 18:03:40' AS DATETIME)
WHERE id = '1855'
When I run this against a SQL Server database from within the application, I get the following error:
System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
But if I take the piece of SQL and run it from SQL Management Studio, it will run without issue.
Any ideas what may be causing this issue?
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy
select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy
select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")
Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').
For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)
It's a date format issue. In Ireland the standard date format for the 28th of March would be "28-03-2011", whereas "03/28/2011" is the standard for the USA (among many others).
I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.
You could use next function to initialize your DateTime variable:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
JAVA8: Use LocalDateTime.now().toString()
i faced this issue where i was using SQL it is different from MYSQL
the solution was puting in this format:
=date('m-d-y h:m:s');
rather than
=date('y-m-d h:m:s');

Get UTC date out of SQL Server & show in grid as local time

I've got a table in SQL Server 2005 that has a datetime column holding dates in UTC form. I want clients to call the a .NET server app and the server will return a DataTable with records to be bound client side to a DataGridView.
** On the client the dates should be displayed in local time **, clients will be in may regions of the world.
Does anyone have any tips on achieving this?
I could of course add a few lines to loop through and update the dates in the table before display but I can't help feeling there's got to be some snazzy funky way of doing this.
TA!!
DateTime.ToLocalTime Is what you're looking for.
Essentially, the fact that you're calling the method tells the DateTime object to add the current culture's offset from UTC and return the result. DateTime.ToUniversalTime does the opposite.
First of all, make sure that the DATETIME values in your tables are stored as UTC values.
After that when you read them, the "client" application can convert them to local datetime (whatever that may be).
When inserting/updating stuff make sure you convert from local to utc before storing in the db.

SQL Server 2005 vs. ASP.net datetime format confusion

I've found a similar question on stack overflow, but it didn't really answer the question I have. I need to make sure that my asp.net application is formatting the date dd/mm/yyyy the same as my SQL Server 2005.
How do I verify the date culture (if that's what it's called) of the server matches how I've programmed my app? Are there specific database settings and OS settings? Is it table-specific? I don't want to transpose my days and months.
thank you
When you get a DateTime out of the database, it should be in a non-cultured format (like the DateTime object, based on the number of ticks since a certain date). It is only when you are converting that value into a string that you need to be concerned with culture. In those cases, you can use yourDateTimeValue.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) to make sure that the information displays correctly.
I belive that if you use SqlParameters ADO.NET will take care of the rest and you don't have to worry about it. Besides, it's good for defending against SQL Injection attacks too! :)
** Watch out because SQL DateTime columns are non-nullable and their minimum value is 1/1/1753 while .net DateTimes are non-nullable with min values of 1/1/0001. **
If you're pulling data from a real DateTime column, by default it will always be in the same standard format. For saving the data to the column, you might want to specify the SqlDbType.DateTime in your parameter.
i ripped this off of http://bytes.com/forum/thread767920.html :
com.Parameters.Add("#adate", SqlDbType.DateTime).Value = DateTime.Now;
Well, if you keep datetime fields in the DB you shouldn't worry about it.
As long as you keep the dates in app strongly typed (DateTime variables) and send the dates through prepared statements with DBParameter/SqlParameter your DB will take them as is.
If you use strings to hold your dates in code, some casts will ensure you send the right values:
string sqlCmd = #"SELECT *
FROM MyTable
WHERE MyDateField = CONVERT(datetime, '{0}', 101)";
// assuming myDateString is a string with a date in the local format
sqlCmd = string.Format(sqlCmd,
Convert.ToDateTime(myDateString).ToString("yyyyMMdd"));
(the code is ugly, but hopefully it gets the point across)
As others have mentioned, you should be OK as far as storing datetimes culturally. What I would recommend is that you store all of your times as standard UTC time. In SQL Server 2005 and older there is no way to store time zone information, but if everything is stored in universal time, you should be OK because the time can be converted to the local time later on.
SQL Server 2008 does have some datatypes that are aware of time zones, and if you're using .NET 3.5 there are tools to assist with time zone handling/conversions.
Definitely keep times in universal format. This will make a world of a difference if you have to work in multiple time zones.

Resources