Javascript time saved incorrectly in sql server table - sql-server

new Date(moment().year(), moment().month(), moment().day(), vm.newHearing().HearingTime().split(":")[0], vm.newHearing().HearingTime().split(":")[1]).toLocaleString()
The client side value for a date column is 11/5/2013 10:15:00 AM. The time is selected from HTML5 time input control.
When I check in database after saving the entity, it shows me incorrect time value:
11/5/2013 3:15:00 PM

It appears that you are using moment.js, which is fine except you aren't using it properly
Try this instead:
moment(vm.newHearing().HearingTime(), "HH:mm").toISOString()
That will pass the selected time, on the current day, from the user's local time zone, converted to UTC time and in ISO format.
Now that might not be exactly what you want to do. Depending on your requirements, you might instead want this:
moment.utc(vm.newHearing().HearingTime(), "HH:mm").toISOString()
Which is almost the same thing except that it assumes the input time is already in UTC.
Or you might want this:
moment(vm.newHearing().HearingTime(), "HH:mm").format("YYYY-MM-DDTHH:mm:ss")
This one doesn't try to convert to UTC at all.
For all choices, I emit the date string in ISO8601 format. Since you are sending it back to the server, this is the best choice. When you used toLocaleString, that generates a format that is appropriat for display only.

Related

Converting string date from one timezone to UTC in Datastage

I would like to convert dates I receive from timezone 'Europe/Warsaw' to UTC. I have tried to find suitable libraries in C to create a Datastage routine. I did not find anything that would allow to flexibly change the source timezone keeping in mind the change from summer to winter time (daylight). Another way is to use a database function, e.g. in DB2, but currently I am trying to solve the problem without creating stored procedures. Anyone solved a similar problem?
I get the input date in the format 'YYYY-MM-DD HH:MI:SS',
Input Timezone = 'Europe/Warsaw',
Output Timezone = 'UTC'.
I would like to create a solution that would allow me to swap e.g. Input Zone, something passed by parameter e.g. 'Europe/London'. I cannot rely on the system time unfortunately.

timezone conversion using date-fns

I’m trying to work with date-fns-tz in my react-based webpage and couldn’t make the following use-case to work.
I have a date input in a form that should be submitted to the backend that stores the data in local timezone.
A user in GMT+2 timezone selects 14:00 on 1/Feb/2021 in the UI, which correlates to 1612180800 timestamp (as the UI was opened in GMT+2), but it should eventually get sent to the backend as 14:00 in GMT-8, which is actually 1612216800 timestamp.
What’s the right way to get this conversion (from 1612180800 --> 1612216800 ) to work?
I tried to work with various date-fns functions, but hadn’t found the right one.
You'll need two things to make this work correctly:
An IANA time zone identifier for the intended target time zone, such as 'America/Los_Angeles', rather than just an offset from UTC.
See "Time Zone != Offset" in the timezone tag wiki.
A library that supports providing input in a specific time zone.
Since you asked about date-fns, you should consider using the date-fns-tz add-on library.
Alternatively you could use Luxon for this.
In the past I might have recommended Moment with Moment-TimeZone, but you should review Moment's project status page before choosing this option.
Sticking with date-fns and date-fns-tz, the use case you gave is the very one described in the docs for the zonedTimeToUtc function, which I'll copy here:
Say a user is asked to input the date/time and time zone of an event. A date/time picker will typically return a Date instance with the chosen date, in the user's local time zone, and a select input might provide the actual IANA time zone name.
In order to work with this info effectively it is necessary to find the equivalent UTC time:
import { zonedTimeToUtc } from 'date-fns-tz'
const date = getDatePickerValue() // e.g. 2014-06-25 10:00:00 (picked in any time zone)
const timeZone = getTimeZoneValue() // e.g. America/Los_Angeles
const utcDate = zonedTimeToUtc(date, timeZone) // In June 10am in Los Angeles is 5pm UTC
postToServer(utcDate.toISOString(), timeZone) // post 2014-06-25T17:00:00.000Z, America/Los_Angeles
In your case, the only change is that at the very end instead of calling utcDate.toISOString() you'll call utcDate.getTime().
Note that you'll still want to divide by 1000 if you intend to pass timestamps in seconds rather than the milliseconds precision offered by the Date object.
You can use 'moment' to convert timezone.
1.Create a moment with your date time, specifying that this is expressed as utc, with moment.utc()
2.convert it to your timezone with moment.tz()
For example
moment.utc(t, 'YYYY-MM-DD HH:mm:ss')
.tz("America/Chicago")
.format('l');

Date from angular(timezone) to server (utc) then utc to Timezone

I have an issue with getting dates back in the right timezone.
Firs at all in the local machine, everything works fine but not in the server: the server is hosted in USA and the clients mostly are in Australia.
So a date is sent from angular app("12/23/2015 11:00:00 AM") to the server, the server store a date as utc in the database, until this point everything is working(I checked and the date is stored in the right utc)
book.StartDateTime = TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(book.StartDateTime.Value, DateTimeKind.Unspecified), ToolsHelper.OlsonTimeZoneToTimeZoneInfo(locationDetails.TimeZone)); // book.CreatedDate.Value.ToUniversalTime();
The issue is:
When a client request some dates stored in the database. The date stored in the database is return back to the client like this:
bookview.StartDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.SpecifyKind(bookli.StartDateTime.Value, DateTimeKind.Utc), ToolsHelper.OlsonTimeZoneToTimeZoneInfo(deCompany.TimeZone));
I checked and at this point the date is "12/23/2015 11:00:00 AM" -> the conversion is right in the server(in the server side I put a log),
But in the angular is shown as "12/23/2015 10:00:00 PM"
So apparently the issue is when the date is transferred by the api to the client, maybe when is converted to JSON
I have tried different ways nothing work, I have removed "DateTime.SpecifyKind", I convert the date to string then back to datetime format and nothing seems to work.
What could I do?
A few things:
Your example is not complete, so I can only speculate on some areas. It would be better to show both sides, including how you load and parse the data in Angular, and what the data looks like over the wire.
You shouldn't be sending dates back and forth in a locale-specific format like "12/23/2015 11:00:00 AM". You might use those in your UI, but they're not appropriate over the wire (in your JSON). Instead, you should be using ISO8601/RFC3339, such as "2015-12-23T11:00:00Z". (You probably are already doing this if you're using WebAPI.)
A DateTime object when serialized to ISO8601 format is coupled with the associated DateTimeKind in the Kind property.
If the Kind is Utc, then the ISO8601 string will end with a Z.
If the Kind is Local, then the ISO8601 string will end with the machine-local offset for that timestamp, such as -08:00.
If the Kind is Unspecified, then the ISO8601 string will not have either Z or offset - which means that it cannot unambiguously represent a specific moment in time.
This is ultimately the cause of the error. You're converting the DateTime to another time zone, which leaves it with Unspecified kind, which then gets serialized without an offset - so on the client side that gets interpreted (probably) in the local time zone of the browser.
A better approach is to use DateTimeOffset instead of DateTime. Then you don't have to worry about Kind, and the offset is always present. If you change your bookview.StartDateTime to a DateTimeOffset type, you can do something like this to fix the problem:
DateTimeOffset dto = new DateTimeOffset(bookli.StartDateTime.Value, TimeSpan.Zero);
bookView.StartDTO = TimeZoneInfo.ConvertTime(dto, ToolsHelper.OlsonTimeZoneToTimeZoneInfo(deCompany.TimeZone));
That will ensure that the offset gets persisted in the data.
On the client side, pay careful attention to how the ISO string gets parsed. if it's loaded into a Date object, then it will indeed be converted to the client's time zone. Instead, you might take a look at moment.js for client-side time formatting. In particular, use moment.parseZone to keep the value in the same offset that it was presented. For example:
var s = moment.parseZone("2015-12-31T11:00:00+00:00").format("L LT"); // "12/31/2015 11:00 AM"
In commented code, you also showed a call to DateTime.ToUniversalTime - be very careful with that. If the source kind is Unspecified, it is treated as Local. Therefore, the local time zone of the computer is reflected in the converted value. It's better to avoid ToUniversalTime and ToLocalTime entirely. Use only the conversion methods on TimeZoneInfo.
ToolsHelper.OlsonTimeZoneToTimeZoneInfo isn't something we know about either. But I'll assume it does a CLDR mapping similar to this one. However, if you're working with Olson time zones anyway, the better approach would be to not use TimeZoneInfo at all. Instead, use Noda Time, with it's native support for tzdb time zones.

AngularJS layered date filter for database submission

I am having trouble with date submissions to a database. When date and time are both needed, I parse the values from the database as a timestamp, which gives me the value of the date and time in milliseconds since 1970. Using the AngularJS date filter, I am able to display the value in a user-friendly way.
$filter('date')(1380292078000, 'MM/dd/yyyy hh:mm a'); => 09/27/2013 10:27 AM
But this format as a timestamp when I send the value back to the database, my code throws an error. The database wants the date to be displayed in a different format.
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss
So I add a second filter to convert the value date representation of the millisecond count (the user might have changed the value), but I am just getting a clone of the first date representation.
$filter('date')('09/27/2013 10:27 AM', 'yyyy-mm-dd hh:mm:ss') => 09/27/2013 10:27 AM
Here is a link to the fiddle I wrote to test this. Are we not able to stack filter conversions on top of each other? I had a thought to convert the first conversion result into milliseconds to use as a source for the second conversion, but I didn't see a method to accomplish this in the date documentation. If that would be the only solution, though, I am sure I could whip something up. Because Java has mostly deprecated functions to work with dates, I feel it would be simpler to handle this on the Javascript/AngularJS side.
The date filter will only work with a JSON date string (see source).
You can get around your problem by converting to a date object:
$scope.date2 = $filter('date')(new Date($scope.date), 'yyyy-MM-dd hh:mm:ss')
See updated fiddle
However... You should be validating and formatting this input on the server side. You can't trust data coming from a javascript application to be in the correct or expected format. I'd recommend just posting back $scope.date and allowing the server to format in your database format. By doing the yyyy-MM-dd hh:mm:ss formatting on the client-side, you're tightly coupling your user interface to database implementation and that's generally considered a bad idea.

Validating Date Parameter in SQL Server Stored Procedure

I've written a stored procedure that takes in a date parameter. My concern is that there will be confusion between American and British date formats. What is the best way to ensure that there is no ambiguity between dates such as 02/12/2008. One possibility would be for users to enter a date in a format such as 20081202 (yyyymmdd). Is there any way to validate that without using sub strings? Alternatively dates could be entered as 02-Dec-2008(dd-mmm-yyyy), but again verification is not trivial and there are potential issues with users who do not use English.
Further to the first three answers . . . One issue is that I'm expecting this stored proc to be called directly without a front end so validation ouside of the proc is not an option. Is it a good idea to take the day, month and year as separate parameters?
You won't have any problems whatsoever if you'd use parameters in your sproc:
create proc dbo.Sproc
#date datetime
as
...
If you declare the parameter as being of type DATETIME or one of the other typed date/time types in SQL Server, which you should, then there is no ambiguity; it represents a particular date and time. The type of validation you're talking about should happen outside the stored procedure, not inside.
OK from your comments and edit, it appears the issue is with the way people call the SP rather than actually within it. To that end, you simply need to train your users to use sortable date format, i.e.
yyyy-MM-dd HH:mm:ss
And then there is no ambiguity. Anybody who is allowed near a database should be aware of localisation issues and should always be using a non-ambiguous format like this one when entering dates.
I've ended up taking a string paramater for the date and require users to enter the month as a word. I check the input is a valid date by converting it to date. To ensure the month is entered as a word, I use the like comparator to compare the input string with "%Jan%" or "%Feb%" or "%Mar%" etc.
If your proc accepts the date as a datetime parameter then there is little you can do to validate that the desired format is ddmmyyyy and not mmddyyyy. It all depends on how the user entered the date and how it was passed to SQL.
For example: On a web page i could add a parameter like this
command.Parameters.AddWithValue("#mydate",mydateVar.ToString("dd/MM/yyyy"));
OR
command.Parameters.AddWithValue("#mydate",mydateVar.ToString("MM/dd/yyyy"));
And SQL will just insert what its given as long as the string can be cast to a date correctly. It wont know the format you want to use so it will try to cast to its system default format.
A solution i use although it may not be applicable in your situation is to have users enter all dates in whatever frontend you have in the dd-MMM-yyyy format. I can then be sure of the format before i insert into the DB. I use that format everywhere to keep it all the same throughout the app.
You said that you are expecting this stored proc to be called directly without a front end and validation ouside of the proc is not an option.
In that case the users will be inserting data directly, I also believe that in this case it is for internal use only (as the stored proc is going to be called directly)
So I think you have 2 options
if you have disciplined users you can agree on one of the safe formats: ISO yyyyddmm, or ISO8601 yyyy-mm-dd Thh:mm:ss:mmm if you need a time part as well
otherwise take 3 parameters: year, month, year and perform some validation inside the stored procedure
I say take a datetime and train them to use the ODBC canonical form of a date as in this example:
EXECUTE uspMyProc {d '2009-02-11'}
If you take a date that you have to parse, whether it be a string or the year, month and day as separate integer arguments, then you have to deal with days out of range for the month and year. Some functions that take those automatically advance or move backwards the day on you. Thus the trick of sending 0 for the day and getting the last day of the previous month. Others return an error. But handling that stuff yourself is probably not worth reinventing the wheel.
If you absolutely have to because novices will be running it directly (why would novices be running stored procedures directly?), I'd take three separate arguments and pass the concatenated date as a string in the format YYYY-MM-DD through ISDATE to verify the parameters and exit if it isn't valid.

Resources