I am developing a Spring/Hibernate web application. I have a DataTranseferObject where the input from the jsp page is stored to be used by different services and eventually saved to a database.
One of the fields in the jsp page is deliveryDate. I want to store it as a date type in the database:
from delivery.java
#Column(name = "DELIVERY_DATE")
private Date deliveryDate;
public void setDeliveryDate(Date deliveryDate){
this.deliveryDate= deliveryDate;
}
public Date getDeliveryDate(){
return deliveryDate;
}
I am trying to validate the field in the jsp page so that only the "yyyy-MM-dd" format is allowed. To do this I have the deliveryDate as a String type in the DataTransferObject and I'm validating it with the #Pattern annotation as such:
#Pattern(regexp="((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])", message="please enter date in fromat yyyy-MM-dd")
#NotNull(message="delivery date is a required field")
private String deliveryDate;
Since I want to store it in the database as a Date type I need to convert the String to a Date type. This I am trying to do using a service:
#Transactional
public Date stringToDateConversion(String stringDate){
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date) formatter.parse(stringDate);
return date;
}
but it's not working since formatter.parse(stringDate) gives "Unhandled exception type ParseException"
I need the service to return a Date type so I can use it in the controller:
Date deliveryDate= deliveryService.stringToDateConversion(deliveryDto.getDeliveryDate());
delivery.setDeliveryDate(deliveryDate);
How do I correctly convert the String to a Date type and return a Date type?
Thanks for the help!
/D
Just handle ParseException with call of parsing String to Date
DateFormat formatter = null;
java.util.Date date = null;
formatter = new SimpleDateFormat("yyyy-MM-dd");
try{
date = formatter.parse(stringDate);
//if you want you can convert it to `java.sql.Date`
}catch(ParseException ex){//do whatever you would like to}
return date;
Related
I have a column called start_date in database and the field has a mapping in model class like
#Column(name = "start_date")
#Temporal(TemporalType.TIMESTAMP)
Date startDate
and in my pojo the same field I have as
String startDate;
from UI I am getting the string value and I want to convert that string to date and store into database
modelObj.setStartDate(parse(pojoObj.getStartDate())
and here is the parse() method
private Date parse(String dateValue){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(dateValue);
return date;
}
this code is working fine when I am providing date in yyyy-MM-dd format but not working in dd-MM-yyyy or yyyy-MMM-dd or MMM dd, yyyy any other format.
can I someone help me how can I persist the date field irrespective it's format.
As String I am able to store but I want to store it as date.
I give you a solution, the database uses BIGINT (20),and Pojo use "Long".
When saving to the database, use a timestamp of length 13, Only need to convert to timestamp when receiving the parameter, and convert the timestamp to any format when returning data.
You could iterate over all your date formats and try to parse the input to a date.
If you can parse exactly one input to a date then you are fine.
If you cannot parse the input, then you need to add a date format to your list.
If you can parse the input to more than one date and the dates are not the same, then you need to think how to proceed :-D
The code could look like
private Date parse(String dateValue) {
final List<SimpleDateFormat> simpleDateFormats = Arrays.asList(
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("dd.MM.yyyy"));
final List<Date> dateCandidates = simpleDateFormats.stream()
.map(formatter -> tryParse(formatter, dateValue))
.filter(Objects::nonNull)
// check if there is more than one date
.collect(Collectors.toList());
if (dateCandidates.isEmpty()) {
throw new RuntimeException(String.format("Unsupported date format %s", dateValue));
}
if (dateCandidates.size() > 1) {
// check if all dates are the same, otherwise throw exception since your input is ambigious
}
return dateCandidates.get(0);
}
private Date tryParse(SimpleDateFormat formatter, String dateValue) {
try {
return formatter.parse(dateValue);
} catch (ParseException e) {
return null;
}
}
dob : any = "15-05-2001";
When sending to server it returns the error Could not read document: Can not construct instance of java.util.Date from String value '15-05-2001': not a valid representation (error: Failed to parse Date value '15-05-2001': Can not parse date \"15-05-2001\": not compatible with any of standard forms (\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\", \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\", \"EEE, dd MMM yyyy HH:mm:ss zzz\", \"yyyy-MM-dd\"))\n
In Angular code tried to convert the the date
dob = new Date(moment(dob, "DD-mm-yyyy").format("MM-DD-YYYY")).getTime();
returns 1581710400000
which returns wrong date, but server accepted the input.
How can I format this date, so that I can send the required date and server accepts same.
Same problem occurred and my solution was i have converted datetime into toLocalString.
var dateTime = new Date();
var sendObj = dateTime.now().toLocalString();
UPDATE:
dob = "15-05-2001";
dob = new Date(moment(this.dob, "dd-MM-YYYY").format()).getTime();
You can create an Advice at backend similar to:
#ControllerAdvice
public class DateAdvice{
#InitBinder
public void initBinder(WebDataBinder binder){
binder.regisyerCustomEditor(Date.class, new PropertEditorSupport(){
public void setAsTest(String text){
//convert to date from this text.
setValue(convertToDate(text));
}
}
}
}
With this you can write all possible combinations to parse the date.
Another way is to change your angular date to follow YYYY-MM-DD format.
I'm trying to pass a java util date to my json response without succes.
If i System.out.println the dates i get "1970-01-01 01:00:00.263" correct format.
System.out.println("from date: " + fromDate);
System.out.println("to date: " + toDate);
// from date: 1970-01-01 01:00:00.022
// to date: 1970-01-01 01:00:00.263
// in my json i get
// from date: 22
// to date: 263
if i pass my date to the json return i get " 263 " only (the last part of the timestamp) ?
how can i format the date so i get the whole date (YY-MM-DD, hour-min-sec) instead of just the last part of the timestamp ?
the model object
public class testSomething {
boolean status;
String msg;
Date fromDate;
Date toDate;
public testSomething(boolean status, String msg, Date fromDate, Date toDate) {
this.status = status;
this.msg = msg;
this.fromDate = fromDate;
this.toDate = toDate;
}
the return value
Date fromDate = dates.get(0);
Date toDate = (Date) dates.get(dates.size() - 1);
return new testSomething(true, "msg here", fromDate, toDate);
Something like this will do ...
long timestamp = fromDate.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY/MM/dd HH-mm-ss");
System.out.println(dateFormat.format(timestamp));
fixed it by adding spring.jackson.date-format=(yyyy-MM-dd HH:mm:ss) to my application.properties file
The default conversion is to send the milliseconds since the Epoch (date.getMillis()). There are two reasons for this:
Readability is not a concern for computers.
This time format is independent of the time zone. That means you can send the date to another computer and it will display the same point in time.
Depending on your JSON framework, there are different ways to install data converters. Jackson has several third-party datatype modules for this purpose and you can install your own in your ObjectMapper.
In Java Spring I wanted to send the data & time to a object through a PUT which uses java.sql.Date in the object. I was using json to send it and this is the format I used
public class MyEntityClass {
private String username;
private Date dateTime;
}
And the Json Format I used is,
{
"username": "selena31",
"dateTime":"2017-01-23T12:34:56"
}
And it worked for me :)
I'm working with the Vaadin Framework at the moment. I want to convert the string in my DateField to Date. So I have two classes, one is the view and the other should contain the values which I save with data binding.
This is the DateField in the view:
timestart = new DateField("");
timestart.setId("timestart");
timestart.setDateFormat("yyyy-MM-dd HH:mm");
timestart.setValue(new Date());
timestart.setResolution(Resolution.MINUTE);
timestart.setConverter( XXX ); // Here i don't know what to do
layout.addComponent(timestart, 3, 2);
In the same class the data binding:
binder.bind(timestart, "timestart");
//This part is working
And in my other class:
private Date timestart;
I want to save this timestart in a database, so i need a formatted value like above yyyy-MM-dd HH:mm but when I do it without timestart.setConverter I am getting a date like Wed Jul 16 11:11:00 CEST 2014.
How should I do this ?
You need to format the Date in your bean class. Not in your View code.
private SimpleDateFormat dateFormat;
private Date timestart;
public ConstructorOfYourClass{
timestart = new Date(); //Default date
//Your prefered date format
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
}
//... other Code ...
//Getter method of your Date
public String getdateFormat(){
return dateFormat.format(timestart);
}
Is it possible to do format a date of type String using a date formatter? I want to store my Date and Time in the Event class as Strings so that I don't need to convert the Strings loaded from a MYSQL database (using the types DATE and TIME) back into Date types so they can be stored in new Event objects. MySQL only accepts DATE in the format of YYYY-MM-DD and TIME in the format of HH:MM:SS but i want these to be formatted differently when i go to print them out in my program.
When i run this code i get an Cannot format given Object as a Date at java.text.DateFormat.format(Unknown Source) error. If i try using parse() it won't compile because it only accepts Dates.
Main class
public Main() {
ArrayList<Event> events = new ArrayList<Event>();
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:MM:SS");
private SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
//Stores current time and date
Date date;
Date time;
String d = "";
String t = "";
d= dateFormat.parse(date);
t= timeFormat.parse(time);
events.add(d, t);
//Print out newly formatted date and time when loaded from mysql
System.out.println(events.get(0).printDate());
System.out.println(events.get(0).printTime());
}
Events class
public class Event {
private String date;
private String time;
public Event(String d, String t) {
date = d;
time = t;
}
public String printDate() {
SimpleDateFormat format = new SimpleDateFormat("DD/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
public String printTime() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String newTime = format.format(time);
return newTime;
}
}
In Event, you should use Date type for date and time field.
This is a more appropriate representation for date and time value. And with them, you can use DateFormat to do whatever formatting you want
(It will be even better to use Joda time LocalDate and LocalTime for your date and time, but that's a bit off topic)
You can't format your dates because they are String objects and SimpleDateFormat needs Date objects.
You should consider a different way of storing them (either as Date or Calendar). See below:
public class Event
{
private Date date;
private Date time;
public Event(String d, String t)
{
String[] details = d.split("\\-");
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
date = c.getTime();
details = t.split(":");
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
time = c.getTime();
}
public String printDate()
{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
// rest of you class can stay the way it is
}
You can format java.util.Date or java.sql.Date (which is subclass of java.util.Date) using date formatter, eg:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = df.format(date);
Using jdbc ResultSet getDate() method you can obtain java.sql.Date object which you can print in any format using method above
Similar techniques can also be used to parse string in any format into a java.util.Date object
Date date = df.parse(dateStr);
Check the javadoc for the right formatting codes. Try this:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");