theendcomplete theendcomplete -4 years ago 127
Java Question

Trouble converting String to Date in a Java Servlet

I have a JSP form with Bootstrap datepickers

the code of datepickers' functions is:

$(function () {
$('#startDate').datetimepicker({
useCurrent: false, //Important! See issue #1075
sideBySide: true,
locale: 'ru',
defaultDate: moment().add(1, 'days'),
format: 'DD.MM.YYYY, HH:mm'
});
$('#endDate').datetimepicker({
useCurrent: false, //Important! See issue #1075
sideBySide: true,
locale: 'ru',
defaultDate: moment().add(2, 'days'),
format: 'DD.MM.YYYY, HH:mm'
});
$("#startDate").on("dp.change", function (e) {
$('#endDate').data("DateTimePicker").minDate(e.date);

});
$("#endDate").on("dp.change", function (e) {
$('#startDate').data("DateTimePicker").maxDate(e.date);
});
});
</script>


I send data from this fields to servlet:

order.setStartDate(convertStringToDate(request.getParameter("startDate")));


This is the code of function convertStringToDate:

private Date convertStringToDate(String string) {
Date date = new Date();
Locale russianLocale = new Locale.Builder().setLanguage("ru").setRegion("RU").build();
try {
date = new SimpleDateFormat("DD.MM.YYYY, HH:mm",russianLocale).parse(string);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}


The string looks like "16.03.2017, 09:22"

The problem is:
no matter what value I give to this function, it returns date "Mon Dec 26 09:22:00 MSK 2016". The Time value is current, but the date is always the same


Can't figure it out by myself :|

Thank everybody for help

Answer Source

Your date format is incorrect. Use this line to replace the one in your code:

date = new SimpleDateFormat("dd.MM.yyyy, HH:mm", russianLocale).parse(string);

Full code:

private static Date convertStringToDate(String string) {
    Date date = new Date();
    Locale russianLocale = new Locale.Builder().setLanguage("ru").setRegion("RU").build();
    try {
        date = new SimpleDateFormat("dd.MM.yyyy, HH:mm", russianLocale).parse(string);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download