-3

I have a datetime picker.the user selects the date and time from datetime picker,and in servlet I get it using request.getParameter("");

Now how to parse the string to date in java as while inserting in database the datatype is datetime.

blackpanther
  • 10,998
  • 11
  • 48
  • 78
user13763
  • 83
  • 7

4 Answers4

2

For example:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
Date d = null;
d = parser.parse("String that is formatted as the above date format");

You really should have been able to find that on your own, there are so many examples if you google it.

SvenT23
  • 667
  • 6
  • 19
0

As you tag this question in mysql also, so i can suggest you how you can do it in mysql. You can pass string through java and convert it at the time of insertion.

STR_TO_DATE('02-Dec-2011','%d-%M-%Y %h:%m:%s')
Zafar Malik
  • 6,734
  • 2
  • 19
  • 30
0

Here is an example for parsing date in SimpleDateFormat

String string = "2014-04-21 17:35:00";
    Calendar calender = Calendar.getInstance();
    DateFormat format = new SimpleDateFormat( "yyyy-MM-dd kk:mm:ss");
    Date date;
    date = format.parse( string );
    calender.setTime(date);
    System.out.println("Day of week: " + calender.get(Calendar.DAY_OF_WEEK)); //2 is monday
    System.out.println("Day of the month: " + calender.get(Calendar.DAY_OF_MONTH));
    System.out.println("Month: " + calender.get(Calendar.MONTH)); //0 is january 3 is april
    System.out.println("Year: " + calender.get(Calendar.YEAR));
    System.out.println("Hour: " + calender.get(Calendar.HOUR_OF_DAY));
    System.out.println("Minutes: " + calender.get(Calendar.MINUTE));
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
-2

What about June 2009 as you can not say its a date you need to make it a date by adding a day in this month-year format. Ex.. add first day of month here and make it 1 June 2009 then parse it in desired format.

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

   public class Test {

      public static void main(String[] args) throws IOException, ParseException 
      { 
          String dateStr = "28 June 2009";
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
          System.out.println(sdf.format(new Date(dateStr)));
      }
   }
Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
hizbul25
  • 3,829
  • 4
  • 26
  • 39