Parsing a date object

I need to be able to parse out the month, day of month and the time from a date object into separate fields. I know I can use the getTime() method to retrieve the milliseconds which I believe I can work with, but I also need the month and day.

Use the Calendar object.
Date myDate = ....;
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int day = cal.get(Calendar.DAY);
int month = cal.get(Calendar.MONTH);Note that the month returned by the Calendar class is ZERO based.
ie 0 = Jan, 1 = Feb, 2=Mar.
Of possible use to you would be the java.text.SimpleDateFormat class which converts between Dates and Strings for you.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("15/09/2005");Check out the API for java.util.Date, java.util.Calendar and java.text.SimpleDateFormat.
Cheers,
evnafets

Similar Messages

  • Parse Date object for AM/PM

    how do we parse whether it is AM /PM from Date() object?

    You asked this question yesterday already with the same degree of vagueness.
    Please return to your thread from yesterday and continue posting vague dribblings as they occur to you there http://forum.java.sun.com/thread.jspa?threadID=5198538

  • Parsing from string to date object

    How can I convert a time in String format to a Date object?
    ie. 14:30:05(String) to 14:30:05

    How about this?
    String sDate = "14:30:05";
    StringTokenizer tokenizer = new StringTokenizer(sDate, ":");
    Calendar calendar = new Calendar();
    int hour = Integer.parseInt(tokenizer.nextToken());
    int minute = Integer.parseInt(tokenizer.nextToken());
    int second = Integer.parseInt(tokenizer.nextToken());
    calendar.set(Calendar.HOUR_OF_DAY, int hour);
    calendar.set(Calendar.MINUTE, int minute);
    calendar.set(Calendar.SECOND, int second);
    Date dDate = calendar.getTime();I didn't try it, but it should be pretty close (unless you want to use deprecated methods, then it can be shorter...)

  • How to add get Day value in a Date object?

    Hi,
    I am writing a sql statement that has two date values. One I am getting it from the database. The format in the database is MM/DD/YYYY. My first question is how do I convert the format into the java date format, YYYY-MM-DD. The second question is I need to find out what the day is and add 1 to it. How do I get Day value in a Date object?
    Thanks.

    Look at "SimpleDateFormat" and "parse" in the archives.

  • How do you store parsed XML data in an array

    Hi, i am trying to complete a small program which implements the SAX parser to parse an XML file. My problem is that i am writing a custom class to store the parsed data into an array, and then make the array available to the main program via a simple method which returns the array. I know this must be very simple to do, but i seem to have developed a mental block with this part of the program. I can parse the data and print all the elements to the screen, but i just cant figure out how to store all the data elements into the array. I will post the class which is supposed to do this, and ask anyone out there if they know what i'm doing wrong, and also, if there is a more effeicient way of achieving this ( i expect there definitely is!! but i have never used the SAX parser before and am getting confused by the API docs on it!!) Any help very much appreciated.
    Here is my attempt at coding the class to handle the parsed XML data
    class Sink extends org.xml.sax.helpers.DefaultHandler
         implements org.xml.sax.ContentHandler{
    Customer[] customers = new Customer[20];
         int count = 1;
         int x = 0;
         int tagCount = 0;
         String name;
    String custID;
         String username;
         String address;
         String phoneNum;
    public void startElement(String uri, String localName, String rawName, final org.xml.sax.Attributes attributes)throws org.xml.sax.SAXException{
    //count the number of <name> tags in the XML file
         if(rawName.equals("name")){
              tagCount++;
    public void characters(char[] ch, int start, int len){
    //get the current string
         String text = new String(ch, start, len);
         String text1 = text.trim();
    //there are 5 elements for each customer found in the XML file so when the count reaches 6
    // i reset this to 1
         if(count == 6){
         count = count - 5;
         if(text1.length()>0 && count == 1){
              name = text1;
              System.out.println(name);
              }else{
         if(text1.length()>0 && count == 2){
              custID = text1;
              System.out.println(custID);
                   }else{
                   if(text1.length()>0 && count == 3){
                   username = text1;
                   System.out.println(username);
                   }else{
                        if(text1.length()>0 && count == 4){
                        address = text1;
                        System.out.println(address);
                        }else{
                        if(text1.length()>0 && count == 5){
                             phoneNum = text1;
                             System.out.println(phoneNum);
                             //add data to the customer array
                             customers[x] = new Customer(name, custID, username, address, phoneNum);
    // increment the array index counter
                        x = x+1;
                        }//end of if
                        }//end else
                        }//end else
                   }//end else
              }//end else
    }//end of characters method
    public void endDocument(){
         System.out.println("There are " + tagCount +
         " <name> elements.");
    }//end of class Sink
    Before the end of this class i also need to make the array available to the calling program!!
    Any help would be much appreciated
    Thanks
    Iain

    Ok, yer going about this all the wrong way. You shouldn't have to maintain a count of all the elements. Basically you are locking yourself into the XML tags not only all being there but are assuming they are all in the same order. What you should do is in your characters() method, put all of the characters into a string buffer. Then, in endElement() (which you dont use btw, you should) you grab the information that is in the string buffer and store it into your Customer object depending on what the tagName is.
    Also, you should probably use a List to store all the Customer objects and not an single array, it's more dynamic and you arent locked into a set number of Customers.
    I wont do it all for you, but I'll give you a good outline to use.
    public class CustomerHandler extends DefaultHandler {
        private java.util.List customerList;  // List of Customer objects
        private java.util.StringBuffer buf;   // StringBuffer to store the string of characters between the start and end tags
        private Customer customer;  // Customer object that is initialized with each entry.
        public CustomerHandler() {
            customerList = new java.util.ArrayList();   // Initialize the List
            buf = new java.util.StringBuffer();   // Initialize the string buffer
        //  Make your customer list available to other classes
        public java.util.List getCustomerList() {
            return customerList;
        public void startElement(String nsURI, String sName, String tagName, Attributes attributes) throws SAXException {
            // Clear the String Buffer
            //  If the tagName is "Customer" then create a new Customer object
        public void characters(char[] ch, int start, int length) {
            //  append the characters into the string buffer
        public void endElement(String nsURI, String sName, String tagName) throws SAXException {
            // If the tagName is "Customer" add your customer object to the List
            // Place the data from the String Buffer into a String
            //  Depending on the tagName, call the appropriate set method on your customer object
    }

  • Converting Date.toString() back to a Date object for compare

    I know this is beating a dead horse to death but I have wasted a whole day trying to get this to work. Here is the problem.
    I need to convert a Date().toString (format returned: Dec 19, 2006 3:39:58 PM EST) back to a Date object. What I am doing is writting this string a text file and then revisiting it to compare later to a current Date object to find the difference in the two stamps in milliseconds.
    J2SE 1.4.2 being used
    Date date = new Date();
    String newDateStr = log[1].trim(); // entry from log file
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date logDate = dateFormat.parse(newDateStr);
    // get difference between the two
    long timeSpan = date.getTime() - logDate.getTime();
    if(timeSpan > 60000){
        // TO DO
    }So should I look at a different approach at either:
    A) Storing the date/time stamp in the text file
    B) The conversion back to Date object is wrong
    Really appreciate any insight on this.
    Thanks
    JLW
    Message was edited by:
    jlwestsr

    Then my friend you are in the same status as Tim.:o)
    I don't know as much as him and I don't care to write
    an elaborate reply most of the time. :D
    Merry ChristmasSame to you.I don't pretend to know that much, but When I see something I do know, I tend to give examples.
    Most probably that is because at the present time I am in a situation where most of my time is spent waiting for a call from the customer, and the app I am supporting works so well that those calls are few and far between. Lucky for me, they pay me for sitting around and answering questions on a forum.
    At least it is a java forum, where I can justly claim that I am improving my knowledge of java.
    ~Tim

  • Java.util.Calendar returning wrong Date object

    Example: This was my scenario last night. A server in California has date/time of 'Mon Aug 18'. Current time in Indiana is 'Sun Aug 17'. I use Calendar.getInstance(TimeZone.getTimeZone("America/Indiana/Indianapolis")) to return a Calendar instance. I then call the getTime() method on that instance. It should return a Date object relating to that particular time zone. It will not. It defaults back to the server time. When I print out the Calendar instance everything is good, correct date, correct time,etc. WHY WON'T THE getTime() return the correct java.util.Date???
    Following is the output was run today so the dates happened to be the same so focus on the Time. Output includes Server time, new Calendar values, and the Date returned by calendar instance getTime(). See that the Calendar is getting the correct Time.
    SERVER DATE=Mon Aug 18 15:52:13 CEST 2003
    CALENDAR INSTANCE=java.util.GregorianCalendar[time=1061214732975,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Indiana/Indianapolis",offset=-18000000,dstSavings=0,useDaylight=false,transitions=35,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=1,ERA=1,YEAR=2003,MONTH=7,WEEK_OF_YEAR=34,WEEK_OF_MONTH=4,DAY_OF_MONTH=18,DAY_OF_YEAR=230,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=8,HOUR_OF_DAY=8,MINUTE=52,SECOND=12,MILLISECOND=975,ZONE_OFFSET=-18000000,DST_OFFSET=0]
    Date from getTime()=Mon Aug 18 15:52:12 CEST 2003

    I got it worked with using DateFormat.parse !
    The trick is to instantiate a new Date object as a result
    of parsing out of 'localized' date string.
    with below code :
    Calendar localCal = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
    localCal.set(Calendar.DATE, 25);
    localCal.set(Calendar.MONTH, 7);
    localCal.set(Calendar.YEAR, 2003);
    localCal.set(Calendar.HOUR_OF_DAY,6);
    localCal.set(Calendar.MINUTE, 38);
    localCal.set(Calendar.SECOND, 11);
    Calendar sinCal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Singapore"));
    sinCal.setTimeInMillis(localCal.getTimeInMillis());
    int date = sinCal.get(Calendar.DATE);
    int month = sinCal.get(Calendar.MONTH);
    int year = sinCal.get(Calendar.YEAR);
    int hour = sinCal.get(Calendar.HOUR_OF_DAY);
    int min = sinCal.get(Calendar.MINUTE);
    int sec = sinCal.get(Calendar.SECOND);
    String sinTimeString = date + "/" + month + "/" + year + " " + hour + ":" + min + ":" + sec;
    System.out.println("VIDSUtil.hostToLocalTime : time string now in SIN time : " + sinTimeString);
    java.util.Date sinTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(sinTimeString);
    System.out.println("time in SIN using Date.toString(): " + sinTime.toString());
    It prints out :
    VIDSUtil.hostToLocalTime : time string now in SIN time : 25/7/2003 21:38:11
    time in SIN using Date.toString(): Fri Jul 25 21:38:11 PDT 2003
    (Ignore the PDT, because Date.toString() defaults where the JVM is running)

  • Parsing a String object that contains the database details in jsp

    Hi All,
    In my project i have a model which is a bean that contains
    a method :-
    UserBean.java
    ....getUserData()
    //the database connection is written here.
    st.executeUpdate("insert ----------");
    In the servlet i am calling the bean,
    ControllerServlet.java
    UserBean ub=new UserBean();
    Object obj=ub.getUserData();
    session.putValue("something",obj); //Here the obj contains all the database datas that is used in insert query
    //By using RequestDispacher i am forwarding this request & the response
    to the jsp page
    ViewJsp.jsp
    String data=(String)session.getValue("something");
    //Here "data" now contains all the database contents that is stored using insert query in the bean
    From here i need to parse the "data" in order to display the contents
    stored in the string "data" in to a html table.
    Plz. do provide a solution for this.It is very Urgent at the moment.
    So that i will be very thankful to u.
    Thanx,
    contactananth

    ok, first of all, in getData, i assume you do a SELECT, not an INSERT,
    so your bean code should look like:
    ResultSet rs = st.executeQuery(...) // or somethig like that
    return rs; // it will contain the data you needand in the jsp you write:
    ResultSet rs = (ResultSet)session.getValue("something");
    instead of
    String data=(String)session.getValue("something");
    i assume you know how to work with a ResultSet

  • How to read date as string (format dd-mm-yyyy) and store it as Date object

    Hi. I would like to read from keyboard String with a date and put this value to Date object. How can i do this???
    Thanks

    Check out java.text.SimpleDateFormat.
    Basically
    String dateString = readUserInput(); // get the string
    SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date myDate = myFormat.parse(dateString);

  • Getting Day, month and year from Date object

    hello everybody,
    Date mydate = Resultset.getDate(indexField);
    Now i would like to get day, month and year from mydate.
    In another words, i'm looking for something equivalent to
    mydate.getDay() as this method is deprecated.
    Can somebody help me out please?
    Thank you in advance,

    swvc2000,
    Here is a sample class that demonstrates two ways in which to do this.import java.util.*;
    import java.text.*;
    public class DateSplitter {
       public static void main(String args[]) {
          /* even though your date is from a result set,
             pretend the following date is your date that
             you are using. The try catch block is used
             because I hand-crafted my date using
             SimpleDateFormat.  Substitute your date.*/
          Date yourDate = null;
          try {
             SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
             yourDate = formatter.parse("05/06/2000");
          } catch (ParseException e) { }
          //the following gets the current date
          Calendar c = Calendar.getInstance();
          //use the calendar object to set it to your date
          c.setTime(yourDate);
          //note months start at zero
          int month = c.get(Calendar.MONTH);
          int year = c.get(Calendar.YEAR);
          int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
          System.out.println("Calendar Month: "+month);
          System.out.println("Calendar Day: "+dayOfMonth);
          System.out.println("Calendar Year: "+year);
          System.out.println();
          /* Simple date format can also be used to strip them
             out of your date object.  When you use it, notice that
             months start at 1.  Also, it returns string values.  If
             you need integer values, you will have to use
             Integer.parseInt() as I did below.  If you are
             only concerned about the string values, just remove
             the Integer.parseInt part. */
          DateFormat formatter = new SimpleDateFormat("M");
          month = Integer.parseInt(formatter.format(yourDate));
          System.out.println("SDF Month: "+ month);
          formatter = new SimpleDateFormat("d");
          dayOfMonth = Integer.parseInt(formatter.format(yourDate));
          System.out.println("SDF Day: "+ dayOfMonth);
          formatter = new SimpleDateFormat("yyyy");
          year = Integer.parseInt(formatter.format(yourDate));
          System.out.println("SDF Year: "+ year);
       }//end main
    }//end DateSplitter classtajenkins

  • How to convert a string to date object?

    I have a string user input for date.
    I want to convert it to Date object to insert it in database.
    How to do it?

    Check the java.text.SimpleDateFormat class. You can use it for parsing dates. API contains good description how to build the format pattern.
    HTH
    Mike

  • How to parse system date to return Date and in yyyy-MM-dd format?

    DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
    java.util.Date date = new java.util.Date ();
    String dateStr = dateFormat.format (date);
    try{
    Date date2 = dateFormat.parse (dateStr);
    }catch(ParseException pe){
    pe.printStackTrace();
    Actually, After parsing the date from string, again it is converted into dfault format i.e. 21 Jan 00.00.00 etc...
    But I want this parsing date in yyyy-MM-dd format and again to return date.
    Can anybody tell me how to do this?

    DateFormat dateFormat = new SimpleDateFormat
    ("yyyy-MM-dd");
    java.util.Date date = new java.util.Date ();
    String dateStr = dateFormat.format (date);
    try{
    Date date2 = dateFormat.parse (dateStr);
    }catch(ParseException pe){
    pe.printStackTrace();
    Actually, After parsing the date from string, again
    it is converted into dfault format i.e. 21 Jan
    00.00.00 etc...
    But I want this parsing date in yyyy-MM-dd format and
    again to return date.
    Can anybody tell me how to do this?A Date object does not have a format, it represents a moment in time. You can use SimpleDateFormat to return a String representing that moment in time in many formats - this does not change the Date object to have that format (which it cannot since it does not contain a format).

  • Coverting Date.toString() back to a new Date object

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html#toString()
    After reading this, I am able to see the output format:
    dow mon dd hh:mm:ss zzz yyyy
    However, my questions is, what if you want to convert this String back into a new Date object later? After reviewing SimpleDateFormatter and other related classes, I find nowhere there is a linked parsing that allows this to be easily coverted back into a new Date object at runtime.
    Am I wrong?
    Thanks.

    Yup, the problem is that I do not have a reference to
    the original string. Is there a simple direct way to
    do this?Wait, I misread this. The original string?
    If you have a Date and get a String out of it, and you later want the original Date, then it's generally better to restructure your app to preserve the original Date. If for some reason that isn't an option (although often things are options when you don't think they are), then you can use SimpleDateFormat to produce a new Date object who value matches the date that the String represents.

  • Parsing a date string

    I need to parse a bunch of date strings in 'UTCG' format (whatever that really means).
    They all look like:
    1 Jan 2001 00:00:00.00
    I can't figure out which of the Java date formats parse this. I've tried many varients of:
    DateFormat.getTimeInstance(DateFormat.MEDIUM,Locale.GERMANY)
    without success.
    Help!!!!

    Here is a bit of info from the API doc - notice in the first paragraph it talks about the Date object, format seems similar. At the bottom of info is the Short, Long, etc, format tyoes, check those out... - Bart
    public abstract class DateFormat
    extends Format
    DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting (i.e., date -> text), parsing (text -> date), and normalization. The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
    DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More detail and examples of using these styles are provided in the method descriptions.
    DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.
    To format a date for the current Locale, use one of the static factory methods:
    myString = DateFormat.getDateInstance().format(myDate);
    If you are formatting multiple dates, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
    DateFormat df = DateFormat.getDateInstance();
    for (int i = 0; i < a.length; ++i) {
    output.println(df.format(myDate) + "; ");
    To format a date for a different Locale, specify it in the call to getDateInstance().
    DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
    You can use a DateFormat to parse also.
    myDate = df.parse(myString);
    Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format. You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale, but generally:
    SHORT is completely numeric, such as 12.13.52 or 3:30pm
    MEDIUM is longer, such as Jan 12, 1952
    LONG is longer, such as January 12, 1952 or 3:30:32pm
    FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.

  • String object to Date object

    Hi,
    I have date as string object "22/04/2008". I want convert this string object to Date object as specified format (dd/MM/yyyy) only.
    Please do the need full.
    Thanks in Advance

    kishoreyakkali wrote:
    Hi,
    I tried as follows
    SimpleDateFormat strOutDt = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj=strOutDt.parse(strTmp);
    System.out.println("dateObj::::" + dateObj);
    Output : Mon Apr 21 00:00:00 IST 2008 A date object is always a wrapper around a millisecond value. It does not contain any formatting information, so you should never print a Date object. You should always convert it to a String using SimpleDateFormat before you print.
    Kaj

Maybe you are looking for

  • Error while trying to activate R/3 datasource from BI with T-Code rsa5

    hi all, i want to activate a particular datasource in R/3 through BI.iam following the below steps. RSA1-->source system>select source system>right click>connection parameters>remote logon>rsa5-select datasource. when iam trying to activate from rsa5

  • An error with the getter method of my tag handler.

    An error occurred at line: 5 in the jsp file: /tagSupportDeom.jsp Generated servlet error: [javac] Compiling 1 source file C:\Apache Group\Tomcat 4.1\work\Standalone\localhost\taglib\tagSupportDeom_jsp.java:62: cannot resolve symbol symbol : class Ta

  • Last stage I get a white box with adobe flash player installler on top

    I go through all the stages, I download, I open it and it installs but at the end I get a white box that says adobe flash player installer on top. I read to uninstall, then reinstall and that is what I did, Now I have no flash player at all. WHY WONT

  • Customer return

    Dear experts,       In customer return scenario during Inspection i used inspection type as 06 lot generated. then i did inspection. But my client require stock posting. For that i assigned Inspection type 05 in material master and i deleted  the ins

  • How do I resolve the iPad error message" cannot verify identity of server"

    I have an iPad 2 model A1395 running iOS 7.2.1 When browsing in Safari I continually get the message: Cannot verify server Identity Would you like to continue anyway?  with the options:  cancel, details, or continue If I select continue, I can go on