I having difficulty trying to solve an error with my date in Spring. I think i have exhausted almost all the solution on stack overflow an i still do not have a solution. I have implement a customDateEditor and i am still get the same error.
I am using the datepicker to select the date on the form.
Error
Failed to convert property value of type java.lang.String to required type java.util.Date for property date; nested exception is
java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "1 March, 2017"
Model
#NotNull(message = "Date field must not be blank.")
#DateTimeFormat(pattern = "dd-MM-yyyy")
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
Controller
#InitBinder
public void allowEmptyDateBinding( WebDataBinder binder )
{
// Custom String Editor. tell spring to set empty values as null instead of empty string.
binder.registerCustomEditor( String.class, new StringTrimmerEditor( true ));
//Custom Date Editor
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy");
simpleDateFormat.setLenient(false);
binder.registerCustomEditor( Date.class, new CustomDateEditor( simpleDateFormat,true));
}
Form
<input th:type="date" class="form-control input-sm datepicker" th:field="*{date}"
placeholder="Date Of Birth"/>
JS Script
$('.datepicker').pickadate({
autoclose: true,
Format: 'dd-MM-yyyy'
});
You are actually using pickadate.js rather than jquery-ui datepicker.
And according to documentation, you are supposed to give 'formatSubmit' property to ensure format of submitted date.
Another issue is your date format for javascript and Java code does not match.
Format 'dd-MM-yyyy' for SimpleDateFormat class will give 01-03-2017,
while for pickatedate.js you need to give 'dd-mm-yyyy' as format.
Therefore, for your "JS script" you should use
$('.datepicker').pickadate({
autoclose: true,
format: 'dd-MM-yyyy',
formatSubmit: 'dd-mm-yyyy'
});
I have MVC 5 application. I have the following workflow:
Select a time from kendo time picker control -> On server converts that time into UTC -> Store UTC time in the database -> Retrieve UTC time from DB -> Bind it back to time picker control
Server’s time zone is Central Standard Time (UTC -6:00)
I have the following steps:
1> User selects a time from the Kendo Time picker control and submits it to the server. For example assume user picks “6:00 PM”
2> On server when I check the posted date value, the Kind property is unspecified. That means if I convert this time to UTC time its going to use server’s time zone to offset the time. However i think we want client’s timezone to offset.
3>So I thought of using Kendo time picker’s value() method which returns the value in string format as Wed May 18 2016 18:00:00 GMT-0500 (Central Daylight Time). This value has time zone info including day light saving.
4>So I added hidden field and on client side I assign string value to hidden field.
5> On server I use the hidden field value to convert into UTC and store it into database. So the above value is stored as 23:00:00 UTC time. ( offset is -5)
So far so good
6> On some other screen now I want to show this value to client.
7> Now when i bind this UTC time back to time picker control, it shows 5:00 PM instead of 6:00 PM ( that is 17:00:00 instead of 18:00:00). That means its offsetting by -6 (that’s Central Standard Time).
Question:
1> When getting the value from time picker it knows the day light time zone. ( as we see in the string value). However when we set the value its not considering day light time zone. Why?
Model
public class Mymodel
{
[DataType(DataType.Time)]
public DateTime OrderTime { get; set; }
public string OrderTimeHidden { get; set; }
}
View: That captures time
#model MyNameSpace.Mymodel
<div>
#(Html.Kendo().TimePickerFor(x => x.OrderTime)
.Format("hh:mm tt")
.Value("08:00 PM")
.HtmlAttributes(new { onkeydown = "javascript:return false;" })
)
#Html.HiddenFor(x=>x.OrderTimeHidden)
</div>
Javascript: That post the model to server
submit.click(function () {
$('#OrderTimeHidden').val($("#OrderTime").getKendoTimePicker().value());
// do post here
$.ajax({...})
})
Controller: That converts and saves time into database
[HttpPost]
public ActionResult Save(MyModel model)
{
var dt = DateTime.ParseExact(model.OrderTimeHidden.Substring(0, 33), "ddd MMM d yyyy HH:mm:ss 'GMT'K", CultureInfo.InvariantCulture);
var entity = new MyEntity();
//OrderTime on entity is of type TimeSpan
entity.OrderTime = dt.ToUniversalTime().TimeOfDay;
SaveToDataBase(entity)
return View("SomeView");
}
Controller: That shows the time on UI
[HttpGet]
public ActionResult ViewTime()
{
var entity = GetEntityFromDataBase();
var model = new MyModel();
model.OrderTime = new DateTime(entity.OrderTime.Ticks, DateTimeKind.Utc)
return View();
}
View: That shows the time on UI
<div>
#Html.Kendo().TimePickerFor(x => x.OrderTime)
.Format("hh:mm tt");
</div>
I am trying to query all customers records using HQL in my Spring/ Hibernate app that have DateAdded between Date1 and Date2 OR LastSeen between Date1 and Date2, so I've build this HQL query in the Repository/ DAO class:
sessionfactory.getCurrentSession().createQuery("from Customer c where c.dateAdded BETWEEN '"+startDate+"' AND '"+endDate+"' OR c.lastSeenDate BETWEEN '"+startDate+"' AND '"+endDate+"'").list();
I've debugged the app to check the startDate and endDate and found that they are sent as:
startDate: Wed Jan 22 01:16:57 HKT 2014
endDate: Wed Jan 29 01:16:57 HKT 2014
In DB, I am 100% sure there is one record at least meeting this query, as this record DateAdded and LastSeen are as follows:
2014-01-23 15:33:38
2014-01-25 15:33:38
So can someone please tell me what I am doing wrong / missing here?
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String frmDate = format.parse(startDate);
String enDate = format.parse(endDate);
sessionfactory.getCurrentSession()
.createQuery("FROM Customer AS c WHERE c.dateAdded BETWEEN :stDate AND :edDate ")
.setParameter("stDate", frmDate)
.setParameter("edDate", enDate)
.list();
hope this will help!
This is an old post, but I figured it might help someone. Setting .setTimeStamp should do the trick.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String frmDate = format.parse(startDate);
String enDate = format.parse(endDate);
sessionfactory.getCurrentSession()
.createQuery("FROM Customer AS c WHERE c.dateAdded BETWEEN :stDate AND :edDate ")
.setTimestamp("stDate", frmDate)
.setTimestamp("edDate", enDate)
.list();
SimpleDateFormat sf=new SimpleDateFormat("dd-MM-YYYY");
String fromDate=null;
String toDate=null;
fromDate=sf.format(startDate);
toDate=sf.format(endDate);
sessionfactory.getCurrentSession().createQuery("from Customer where dateAdded BETWEEN '"+startDate+"' AND '"+endDate+"'");
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 90);
Date fromDate = null, toDate = null;
String fromDateStr = formatter.format(new Date());
String toDateStr = formatter.format(c.getTime());
try {
fromDate = formatter.parse(fromDateStr);
toDate = formatter.parse(toDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
query.setParameter("stDate", fromDate);
query.setParameter("edDate", toDate);
It's important to know that when using BETWEEN “setDate” will truncate the HQL date value passed as parameter and ignore the hours, minutes, seconds. This is very important to note especially if you have an HQL query checking between dates from different days because using “setDate” will interpret the date interval as between midnight of the specified dates.
The solution is to use “setParameter” instead of “setDate” which causes the HQL date values to be interpreted as dates and times.
here's a few examples in my site for those interested http://www.coding-dude.com/wp/java/hql-date-datetime-quick-tip/
I had similar issue. When we use end date (Wed Jan 29), the system looks for Wed Jan 29 00:00:00, which is just like choosing Jan 28. In order to avoid such case, we can add one day to the end date. This also explains why we do not have issue with the start date.
Surprisingly, this issue does not exist when we use hibernate criteria.
You need to annotate with #JsonFormat the same way the date filters and date field as follows:
Class Filter {
...
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy HH:mm", timezone="America/Sao_Paulo")
private Date startDate;
}
Class YourObject {
...
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd/MM/yyyy HH:mm", timezone="America/Sao_Paulo")
private Date DateAdded;
}
The pattern and timezone should be adjusted to your region.
Try something like this:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = df.parse(startDate);
Date toDate = df.parse(endDate);
Criteria criteria = sessionfactory.getCurrentSession().createCriteria(Customer.class)
.add(Restrictions.between("dateAdded", fromDate , toDate ));
List<Customer> listCustomer = criteria.list();
Hope this helps..!!
We are using SolrNet API to Index and Search a set of documents which contains three date fields: Date1, Date2, Date3. The C# class has the following definitions for the three fields
public DateTime? Date1{ get; set; }
public DateTime? Date2{ get; set; }
public DateTime? Date3{ get; set; }
The Solr schema definition is as follows:
<field name="Date1" type="date" indexed="false" stored="true" required="false"/>
<field name="Date2" type="date" indexed="false" stored="true" required="false"/>
<field name="Date3" type="date" indexed="false" stored="true" required="false"/>
When we execute a query with a document which has already been indexed, we get the following values returned in the SolrAdmin interface:
<date name="Date1">0001-01-01T00:00:00Z</date>
<date name="Date2">2010-04-10T08:21:18.281Z</date>
<date name="Date3">2007-12-01T03:09:41.093Z</date>
But when we inspect the C# object which gets returned with the SolrQueryResults, it shows the following:
Date1 : {01-01-0001 12:00:00 AM}
Date2 : null
Date3 : null
The first date is being represented as the datetime min value which is expected. But why are the other dates getting null values when these are valid dates in the UTC format?
Is it better to store the date fields as strings in Solr and use a copy field to store it in the solr date format and use this field for date range queries?
Check that you are returning the Date2 and Date3 fields in your SolrNet query results. e.g. Make sure that you are not limiting the fields with &fl parameter via SolrNet Fields QueryOptions or using a requestHandler on the Solr instance that is filtering fields and does not include those fields.
Please try the below code, Hope it helps
using SolrNet;
public List<ISolrQuery> BuildFitlerQuery(DateTime StartDate, DateTime EndDate, string FiledName)
{
var filter = new List<ISolrQuery>();
if (EndDate.Year != 1)// Will create query when end date value is also send
filter.Add(new SolrQueryByRange<DateTime?>(FiledName, StartDate, EndDate));
else
filter.Add(new SolrQueryByRange<DateTime?>(FiledName, StartDate, null));
return filter;
}
I need some help that might be easy for all of you out there.
I have this mvc3 web app, I just need to convert the display of date format from mm/dd/yyyy hh:mm:ss AM/PM to dd.mm.yyyy HH:MM Military time. I found some solutions but it doesn't work like #item.date.ToString("dd.mm.yyyy")
can someone please? Thanks!
Refer to: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#Y133
This worked for me in a console app:
class Program
{
static void Main(string[] args)
{
//mm/dd/yyyy hh:mm:ss AM/PM to dd.mm.yyyy HH:MM
var date = Convert.ToDateTime("12/13/1980 4:50:34 PM");
Console.WriteLine(date);
var date2 = date.ToString("dd.MM.yyyy HH:mm");
Console.WriteLine(date2);
Console.ReadLine();
}
}
Output:
12/13/1980 4:50:34 PM
13.12.1980 16:50