Set date format in ruby model (sinatra/datamapper) - ruby

I have a ruby model that contains a date attribue which I'd like to be able to pass in as a parameter in the format dd/MM/yyyy.
However, my sqlite3 db stores the data in yyyy-MM-dd format so when a date like 20/10/2010 gets passed in, it will not be read to the database.
I am using the Sinatra framework and using haml for the markup creation.
Do I need to write a helper that takes the date string and converts it to the correct format for the db? Or can I set a format type on the models attribute?
Thanks.

You shouldn't need to worry about the database's internal representation of the date; DataMapper is there to do that for you. You just need to make sure you are passing it a valid Date object.
Check out http://ruby-doc.org/core/classes/Date.html for methods available to the Date class. For your example:
require 'date'
mydate = '20/10/2010'
mydate_obj = Date::strptime(mydate, '%d/%m/%Y')
puts "#{mydate_obj}" # prints 2010-10-20

I don't know if this can help, some time ago I had the same problem: I was using Rack::Utils.escape_html(params[:datetime]) to escape html on user input and if I typed a date in a form field like this "25/02/2013" it would be sent to the DataMapper model like this: 16/02/2013 (with escaped html codes) so it was saving it the wrong way (day ended up being the hour or something similar).
Maybe you are also using "escape_html" method in an awkward way?

Related

How do I get a Django Rest Framework DateTimeField to require timezone information?

I have a Django Rest Framework serializer with a DateTimeField. By default it will deserialize date/time values using the iso-8601 format. However, iso-8601 doesn't require a timezone offset. I need the user to always provide some timezone offset information (or better said, validate agains rfc 3339, a subset of iso-8601).
The field allows you to set a custom list of input_formats, but since Python is unable to parse rfc 3339 formatted dates correctly (i.e. an offset with a colon between the hour and minute part is unsupported) I'm stuck.
The DateTimeField in Django Rest Framework is perfectly capable of parsing rfc 3339 datetime values thanks to it's use of django.utils.dateparse.parse_datetime (it's somewhat more lenient, but that's fine).
parse_datetime either returns a timezone aware datetime instance (with tzinfo zet to a fixed offset) or a naive datetime instance (no tzinfo).
Django Rest Framework's DateTimeField converts any given value to an aware datetime value if settings.USE_TZ is set or the field was given a value for the default_timezone argument, otherwise any value is made naive.
The enforce_timezone method of DateTimeField is responsible for making values aware/naive.
Knowing this, enforcing that parsed values must be timezone aware can be achieved by overriding enforce_timezone and raising a ValidationError if the parsed datetime value is naive:
from django.utils import timezone
class DateTimeFieldWithOffset(serializers.DateTimeField):
default_error_messages = {
'naive': 'Datetime value is missing a timezone offset.'
}
def enforce_timezone(self, value):
if timezone.is_naive(value):
self.fail('naive')
return super().enforce_timezone(value)

Trouble passing DateTime values to WebApi route

I have a WebApi project where I have a method that takes a start date and an end date, runs a report, and returns the results. I'm trying to come up with the route for this and so far its looking like
/api/MarketingEmailStatisticsReports/DateRange/{startDate}/{endDate}
Perhaps there is a better route but that really isn't the problem.
I was testing this by simply opening a browser and typing the URL. If I set the startDate and endDates as DateTime fields, I get a 404 Not Found. If I make them strings, I can enter the method but the dates aren't parsable when I attempt to convert them from strings to actual DateTime values.
I realize that if I use "/" characters in the date that will be a problem so I did attempt to use "-" characters as the separator between the month-day-year values.
After looking at some of the Microsoft documentation, I saw how you can put route constraints to check for a DateTime values as well as a regular expression to make sure the value was entered in the correct format. I have taken this advice and am using the following:
[HttpGet]
[ResponseType(typeof(MarketingEmailStatisticsReport))]
[Route("/api/MarketingEmailStatisticsReports/DateRange/{startDate:datetime:regex(^\\d{4}-\\d{2}-\\d{2}$)/{endDate:datetime:regex(^\\d{4}-\\d{2}-\\d{2}$)}")]
public IHttpActionResult Get(DateTime startDate, DateTime endDate)
I get this exception:
ArgumentException: parsing
"^\d{4}-\d{2}-\d{2}$)/{endDate:datetime:regex(^\d{4}-\d{2}-\d{2}$" -
Too many )'s.
This is the URL I was using:
api/MarketingEmailStatisticsReports/DateRange/2017-05-22/2017-05-23
It doesn't look to me that I have too many ")" characters... What do I need to do to get this to work, or should I pass the dates on the querystring instead?
You forgot to close startDate parameter definition:
.../DateRange/{startDate:datetime:regex(^\\d{4}-\\d{2}-\\d{2}$)}/{endDate:datetime...
^
this curly bracket

SSRS URL acces pass DDMMYY dateformat

How can I pass a date/time parameter to my report via url. I only have access to the DDMMYY format of the date. I know I should tell SSRS what language to use with the
rs:ParameterLanguage=de-DE
But I dont know what language DDMMYY is.
http://<>/ReportServer/Pages/ReportViewer.aspx?/<>/<>/report&para1=801&para2=1000011&DATE=070415&rs:ParameterLanguage=???
Oké, I guess this is not possible, but I added a hidden text parameter to the report so I could convert is with custom vbscript. and let the query decide what to use as the date parameter.

How do I properly validate DateTime in a CRUD situation for a model within an MVC project?

I have users selecting a DateTime using a caldendar/clock popup that allows them to make a selection. However, if they were to go in and edit the date to read something like: 6/12/201 10:36:47 AM instead of 6/12/2012 10:36:47 AM my Action gets past the ModelState.IsValid check and I get an error when the Controller attempts to save the object to the database (rightly so).
How do I properly validate DateTime in this situation? (I want to prevent a user from even being able to 'submit' the form if the datetime is not properly formatted)
Note: I currently have in place jquery.validate and typically (fields not DateTime) I use #Html.ValidationMessageFor(model => model.Field) - This does not appear to do anything for my current DateTime fields when they are formatted inappropriately.
you can simply add date client side validator for you DateTime field using snipet like that:
$(element).rules('add', {
date: true,
});
where "element" is your input for DateTime field.
Are you sure you're importing all of the requisite validation js files? it sounds like your server validation is working OK but the client is doing nothing. I suggest reading the following post by Brad Wilson: link

Passing DateTime into TryUpdateModel

One property of my model is DateTime. I'm working with DateTime format "d.M.yyyy H:mm", i.e. day.month.year. When I pass date like 11.4.2011 (April 11th, 2011) into TryUpdateModel, it comes back as 4.11.2011, i.e. day and month swaps. Is there any way how can I instruct TryUpdateModel to parse datetime value the way I want, not the way system wants?
Thanks,
Antonin
I had the same problem and I discovered that if I use HTTPPost instead of HTTPGet MVC behaves as expected. I don't know why it solves the problem and I am still looking for the full answer to this question.

Resources