I'm getting some troubles with the tag and then updating my Date attribute from a model with the params sent.
Here is my tag:
<g:datePicker name="data" value="${controle.data}" precision="month"
years="${(Calendar.getInstance().get(Calendar.YEAR)-70)..Calendar.getInstance().get(Calendar.YEAR)}"/>
When I println the "params.data" it says "struct", but I can't simply do:
model.data = params.data
the params comes with params.data_month and params.data_year with the respectives values in String like:
[[data:struct], [data_month:1], [data_year:2009]]
I tried to do then:
model.data = new SimpleDateFormat("MM/yyyy").parse("${params.data_month}/${params.data_year}")
but it rejects the value, alerting: "Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'data'"
println model.data
println new SimpleDateFormat("MM/yyyy").parse("${params.data_month}/${params.data_year}")
--shows
2006-01-01 00:00:00.0
Sun Jan 01 00:00:00 BRST 2006
but I can't simply do: model.data =
params.data
Why not? Are you getting an exception, or are you just being mislead by outdated documentation? -
This is a feature since Grails 1.2. Conversion to a Date type will be performed, automatically.
As for the SimpleDateFormat issue, just add a day, like so:
model.data = new SimpleDateFormat("d/MM/yyyy").parse(
"1/${params.data_month}/${params.data_year}")
Related
My date = 1st January, 2015.
I did
date_formatted = date.strftime('%Y%W') which returned "201500"
Then when am trying to do Date.strptime(date_formatted, '%Y%W') it's throwing an invalid date error even though the original string was returned from strptime's counterpart srftime.
Found the solution. Time.strptime(date_formatted, '%Y%W') is what will work here.
I'm getting an error
converting data type nvarchar to datetime.
Where I did mistake?
var exec = db.Database.ExecuteSqlCommand("sp_InsertTicketChat #TicketId,
#FullName, #Description,
#LastCorrespondanceBy,#LastCorrespondanceOn",
new SqlParameter("#TicketId", TicketId),
new SqlParameter("#FullName", FullName),
new SqlParameter("#Description", Description),
new SqlParameter("#LastCorrespondanceBy", FullName),
new SqlParameter("#LastCorrespondanceOn",
DateTime.Now.ToString())
);
This is my stored procedure through which I want to insert data. What can I do ?
INSERT INTO tblTicketChat
(
TicketId,
FullName,
[Description],
LastCorrespondanceOn,
LastCorrespondanceBy
)
VALUES
(
#TicketId,
#FullName,
#Description,
GETDATE(),
#LastCorrespondanceBy)
Now I got the root cause of the issue you were facing.
Ideally, DateTime.Now.ToString() should have got converted to SQL Server Datetime data type when being assigned to the #LastCorrespondanceOn parameter of your stored procedure but it threw an exception.
The reason is date time format settings of your operating system.
The thing is when you perform DateTime.Now.ToString() in your C# language based client code it takes the default settings of date time format from your operating system. Look at the date time format currently set on my windows 10 box:
Due to this setting the code DateTime.Now.ToString() emits 27-07-2017 18:07:37. The output you're seeing is dd-MM-yyyy format.
Now this dd-MM-yyyy date format is not recognizable by SQL Server as per your default language settings.
SQL Server can recognize two date time formats when sent as string from client side
International date format yyyy-MM-dd also known as ISO 8601 .
Date format controlled by user login's dateformat setting. You can run dbcc useroptions command to see the value of setting. For me it is set to mdy
Due to this mismatch in the date time format being sent by your C# code (because of your operating system) and what SQL server can parse, you faced the issue.
When you did the conversion explicitly by date.ToString("yyyy-MM-dd"); you simply aligned it ISO 8601 international date time format supported by SQL Server so it started to work.
The default date time format (ISO 8601) of SQL Server is a configuration of the collation you are using currently which you can check in your SQL Server instance properties as shown below:
It is strongly recommended that you should always use SQL's date time format when passing it in string format as mentioned in this thread.
So you can solve your problem in three ways:
Change the default date format of your OS to align it to SQL Server (Not recommended). It will never be feasible on all client computers where your application runs.
Use custom date format while calling ToString method as you have done to align it to one of the formats supported by SQL Server. Best format is ISO 8601 format which you've used.
Don't convert it to string. Just pass the date time value as is.
var exec = db.Database.ExecuteSqlCommand("sp_InsertTicketChat #TicketId,
#FullName, #Description,
#LastCorrespondanceBy,#LastCorrespondanceOn",
new SqlParameter("#TicketId", TicketId),
new SqlParameter("#FullName", FullName),
new SqlParameter("#Description", Description),
new SqlParameter("#LastCorrespondanceBy", FullName),
new SqlParameter("#LastCorrespondanceOn",
DateTime.Now) //Don't call .ToString here
);
Approach # 3 is the best deal. More details here as to why you shouldn't use strings but the date time data type while dealing with SQL Server datetime columns.
I solve this issues by using MSSQL string formatted (dd-MM-yyyy) in my storedprocedure
I solved this issue by doing some changes.
DateTime date = DateTime.Now;
string strDateTime = date.ToString("yyyy-MM-dd");
var exec = db.Database.ExecuteSqlCommand("sp_InsertTicketChat #TicketId, #FullName, #Description, #LastCorrespondanceOn, #LastCorrespondanceBy",
new SqlParameter("#TicketId", TicketId),
new SqlParameter("#FullName", FullName),
new SqlParameter("#Description", Description),
new SqlParameter("#LastCorrespondanceBy", "raza"),
new SqlParameter("#LastCorrespondanceOn", strDateTime)
);
I'm attempting to convert a string date into a date that can be stored in the database. These are my attempts:
params[:event][:start_date] = '03-21-2016'
DateTime.strptime(params[:event][:start_date], '%Y-%m-%dT%H:%M:%S%z')
or
DateTime.strptime(params[:event][:start_date], '%m-%d-%Y')
However I keep getting an invalid date error. I'm not sure what I'm doing wrong.
One way to do it would be this:
date_string = '03-21-2016'
month, day, year = date_string.split('-').map(&:to_i)
DateTime.new(year, month, day)
You need to understand what each fragment (eg %Y) in the format string ('%Y-%m-%dT%H:%M:%S%z') means: read this.
http://apidock.com/rails/ActiveSupport/TimeWithZone/strftime
Once you know this, you can tailor a format string to the date string you have, or expect to get: in this case, "%m-%d-%Y".
When debugging create a new, basic and simple, version of the code and test that.
require 'date'
params = '03-21-2016'
DateTime.strptime(params, '%m-%d-%Y') # => #<DateTime: 2016-03-21T00:00:00+00:00 ((2457469j,0s,0n),+0s,2299161j)>
Note the order for the format: '%m-%d-%Y', which works. That's the problem with your first attempt, where you tried to use%Y-%m-%d. There is NO month21or day2016`.
Your second attempt is valid but your question makes it appear it doesn't work. You need to be more careful with your testing:
params = {event:{start_date:'03-21-2016'}}
DateTime.strptime(params[:event][:start_date], '%m-%d-%Y') # => #<DateTime: 2016-03-21T00:00:00+00:00 ((2457469j,0s,0n),+0s,2299161j)>
One of my co-workers has written an application in Grails 2.4.4 (I know, it's dated). One problem the app has is that you can enter a date like 2/31/2015 and it will be accepted as valid and will show up in your domain object as 3/3/2015 instead.
Is there any easy way to prevent this from happening using grails? Or do we instead have to rely on client side validation for this particular property?
Thanks.
Assuming that Grails is using DateFormat to parse the date String, the issue is that it's using a lenient Calendar. For example, with lenient set to true (the default), the result is as you described:
import java.text.SimpleDateFormat
def sdf = new SimpleDateFormat('MM/dd/y')
assert sdf.parse('02/31/2015').toString() == 'Tue Mar 03 00:00:00 EST 2015'
But, if you change it to false, you'll get an exception for the same date:
sdf.lenient = false
try {
sdf.parse('02/31/2015').toString() == 'Tue Mar 03 00:00:00 EST 2015'
} catch (java.text.ParseException ex) {
// java.text.ParseException: Unparseable date: "02/31/2015"
println 'Oops'
}
So to handle this validation in your controller, you can
Create a command object.
Have the command object accept the date as a String rather than a Date, and perform the date validation.
Modify the controller action to use the command object instead of params. This may require modifying the GSP code as well.
I had a LocalTime field (using Joda Time) in Grails domain class.
Class WorkDone{
LocalTime duration
}
Now I have altered this field to String (with Text constraint) so that it can support duration larger than 24 hrs.
String duration
The problem is there is already some data in database. And I want to sanitize that data through database migrations in Grails. I am using Postgres which saves LocalTime as Bytea (binary data).
When I call WorkDone.duration it returns me a String of the form:
\xaced0005737200176f72672e6a6f64612e74696d652e4c6f63616c54696d65fffff44abbf29def0200024a000c694c6f63616c4d696c6c69734c000b694368726f6e6f6c6f677974001a4c6f72672f6a6f64612f74696d652f4368726f6e6f6c6f67793b78700000000000000000737200276f72672e6a6f64612e74696d652e6368726f6e6f2e49534f4368726f6e6f6c6f67792453747562a9c811667137502703000078707372001f6f72672e6a6f64612e74696d652e4461746554696d655a6f6e652453747562a62f019a7c321ae30300007870770500035554437878
How can I extract time from this string?
Your data is scaped in bytea Hex format, (starts with \x) take a look at PostgreSQL docs
http://www.postgresql.org/docs/current/static/datatype-binary.html
You have to unescape it before read as ObjectInputStream ang get the LocalTime object, unescape it and then try again as Raphael suggest.
You should have done a data-migration before changing your Data-type to String.
Here is what you should do.
1. Change the Data-type of the field back to LocalTime.
2. Create a new field with String Date.
3. Write a script that would get all date in LocalTime and convert it to String and save it in new field.
4. Once you have your data migrated, delete the old field and then rename your new field to duration.
I ended up doing the following -
grailsChange{
change{
sql.eachRow("Select id,duration from work_done"){
def wdId = it.id
def durationObj = (LocalTime)(new ObjectInputStream(new ByteArrayInputStream(it.duration))).readObject()
durationObj = durationObj.toString().substring(0,8)
WorkDone.executeUpdate("update WorkDone wd set wd.duration=:newDuration" +
"where wd.id=:wdId",
[newDuration:durationObj ,wdId:wdId ])
}
}