Converting a String to Calendar

I have a String which is actually a date in the format yyyyMMdd.
I need to take this String and convert it into a Calendar to do a before() check.
I want to delete dates prior to a certain date.
I am able to use this code to get a String to a Date but I need a String to a Calendar.
String sDateOfDir = null;
sDateOfDir = children;                              
Date dStringToDate = (Date)sdf.parse(sDateOfDir);      
Calendar cal = Calendar.getInstance();
cal.setTime(dStringToDate); // this is still java.util.Date
I need a String to a Calendar
or
can this line of code
cal.setTime(dStringToDate); be formatted to yyyyMMdd
any suggestions thanks in advance

I dont know what I am having such a block today. I am not sure I understand. I have posted my code and I hope you can just point out how I can make this easier.
I am reading in a File Directory with its subfolders.
The subdirs are named with the Date the subdir is created (yyyyMMdd)
I want to delete the subdirs that are older than 30days
public class RemoveFileFolders
     public static String sDirDNE = "Either dir DNE or is not a dir";
     public static String sSuccessFalse = "!success false";
     public static String sNowDeleting = "Now deleting contents of ";
     public static String sForSub = " for subdir(s) prior to ";
     public static java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd");
     public static void main(String[] args)
          File fDir = new File("\\C:\\Dates");
          Calendar cTodayMinusOneMonth = Calendar.getInstance(); //today
          cTodayMinusOneMonth.roll(Calendar.MONTH, false); //today minus one (1) month
          //I want to delete all subdir that are older than 20070821
          System.out.println(sNowDeleting + fDir + sForSub + sdf.format(cTodayMinusOneMonth.getTime()));
          //String sCalToString = null;
          //sCalToString = sdf.format(cTodayMinusOneMonth.getTime()).toString();
          if(fDir.isDirectory())
               String[] children = fDir.list();     
               if (children == null)
                    System.out.println(sDirDNE);
               else
                    try
                         for (int i = 0; i < children.length; i++)
                              String sDateOfDir = null;
                              sDateOfDir = children;
                              Date dStringToDate = (Date)sdf.parse(sDateOfDir);
                              System.out.println("sDateOfDir I am a string " + sDateOfDir);
                              Calendar cal = Calendar.getInstance();
                              //cal.setTime(dStringToDate);
                              cal.before(dStringToDate);
                              //if DateDir is before cTodayMinusOneMonth.roll(Calendar.MONTH, false); //today minus one (1) month
                              //delete that dir
                              if(children[i].equalsIgnoreCase(sDateOfDir))
                                   boolean success = deleteDir(new File(fDir, children[i]));
                                   if (!success)
                                        System.out.println(sSuccessFalse);
                    catch(ParseException pe)
                         System.out.println("ParseException " + pe);
     public static boolean deleteDir(File fDir)
          if (fDir.isDirectory())
               String[] children = fDir.list();
               for (int i = 0; i < children.length; i++)
                    boolean success = deleteDir(new File(fDir, children[i]));
                    if (!success)
                         return false;
          return fDir.delete();

Similar Messages

  • How to convert a String to Calendar ?

    Hello all,
    I need to convert a date which is in the form dd-mon-yyyy to a Calendar. Can any one help me ?. This is my first post here.

    And an example:import java.text.*;
    import java.util.*;
    public class Test {
        public static void main (String[] parameters) {
            try {
                System.out.println (getDate (getCalendar ("17 jun 2003", "dd MMM yyyy"), "d MMMM yyyy"));
            } catch (ParseException exception) {
                exception.printStackTrace (System.err);
                System.exit (- 1);
        private static Calendar getCalendar (String date, String format) throws ParseException {
            Calendar calendar = new GregorianCalendar ();
            calendar.setTime (new SimpleDateFormat (format).parse (date));
            return calendar;
        private static String getDate (Calendar calendar, String format) {
            return new SimpleDateFormat (format).format (calendar.getTime ());
    }Kind regards,
      Levi

  • Convert string to  calendar

    bail me out of this problem
    i got 3 "Calendar" objects : "to" , "from" and "now"
    i got another Sting Object "n"
    where String n = now.toString()
    I have access to "to", "from" and "n"
    and I have to know whether n lies in between "to" and "from"
    The following code does not give right answer
    if(from.before(n) && to.after(n))
    System.out.println("n lies between to and from");
    help me out...

    Create a suitable SimpleDateFormat object and use it to convert your string to a java.util.Date before making the test.
    You probably want Date objects, not Calendar objects. Calendar objects are for doing date calculations - like adding a month to a date or whatever.

  • Converting String to Calendar Object

    Hi,
    I nedd to Change the below String to Calendar Object.i want to show the records which are older than half an hour.any other idea which will solve my problems?
    Fri Aug 17 01:56:40 GMT+05:30 1906
    Thanks in advance.
    Regards:
    Akash.

    Look at
    java.text.SimpleDataFormat

  • How to convert julian Date into Calendar Date

    Hi,
    I want convert julian Date to calendar Date (mm/dd/yyyy or mm/dd/yy format) in java.
    Can any one help me how to convert julian date to calendar Date.
    Thanks,
    Krishore.

    import java.util.*;
    import java.text.*;
    public class jdate {
    Calendar date;
    public jdate(int j)
    date = Calendar.getInstance();
    date.set(Calendar.DAY_OF_YEAR, j);
    public String toString()
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    return (formatter.format( date.getTime() ));
    public static void main(String args[])
    if(args.length == 1)
    int j = Integer.parseInt(args[0]);
    jdate julian = new jdate(j);
    System.out.println("Julian date(" + j + ") = " + julian.toString());
    }

  • How to convert a string

    I have a string "March 2006", that I would like to convert into two dates, one is first date of the month and second is the last date of the month.
    For example:
    String strDate="March 2006"
    Now I want to convert it into two dates:
    03/01/2006 and 03/31/2006 and assign those two dates to two variables.
    I have been trying something like this just to convert string to date but no luck:
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         java.util.Date mydate = new java.util.Date();
         try{
         mydate = sdf.parse("March 2006");
         }catch(ParseException e){}
         System.out.println("Java data object is"+mydate);
    I get following output : Tue Jun 20 10:34:30 CDT 2006

    Thanks for your patience guys. First I am not a java
    expert and just a new bee to Java, and second I guess
    we are going into a different direction here. My
    basic problem is that is there a way to convert
    "March 2006" string to 03/2006? Then once we get
    03/2006, can we find what is the first date ,
    offcourse 01, and what is the last date, which in
    this case is 31?Convert the String to a Date, as you've already been shown how to do
    Use the java.util.Calendar methods to get your last day of the month value (check the javadoc, especially the get method and look at the fields) Post back with any specific questions.
    Good Luck
    Lee
    >
    For example:
    My variable is "March 2006". The end product I want
    is:
    strDate1=03/01/2006
    strDate2=03/31/2006.
    How should I get my end product?
    I can write string manipulation functions to get this
    done,but trying to see if there is an easiest way to
    do this. Thanks.

  • Date condition in BEx is getting converted as String prompt in Crystal

    Hi,
    The Date condition in BEx is getting converted as String prompt in Crystal Reports.
    User is not getting the flexibility to select date using Calendar option because of string type
    Please advice
    Thanks,
    Vishal

    Post your question BEX and B1 and classic SAP data source issues to the Integration Kit forum

  • Converting a String to Date

    I have a String in which i am storing the date which I have retrieved from database. How can I convert this String to a Date object and use Comparator for sorting.
    String strCreatedDate1 = ((CVendorEmployees) vendoremployee1).getCreatedDate().toUpperCase();The date format which I will retrieve from String is mm/dd/yyyy.
    I want to convert this into date and use it for sorting.
    Thanx.

    Date dtTmp = new
    SimpleDateFormat("dd-MM-yyyy").parse(((CVendorEmployee
    s) vendoremployee1).getCreatedDate());
                                  Calendar calendar = Calendar.getInstance();      
                                  calendar.setTime(dtTmp);
    Now you have the date object do what ever you wish toBetter make thatnew SimpleDateFormat("MM/dd/yyyy")And no need for the Calendar stuff if all you want is a Date object.

  • "Property value is not valid" when PropertyGridView tries to convert a string to a custom object type.

    Hi,
    I have a problem with an PropertyGrid enum property that uses a type converter.
    In general it works, but when I double clicking or using the scoll wheel,  an error message appears:
    "Property value is not valid"
    Details: "Object of type 'System.String' cannot be converted to type 'myCompany.myProject.CC_myCustomProperty."
    I noticed that the CommitValue method (in PropertyGridView.cs) tries to convert a string value to a CC_myCustomProperty object.
    Here is the code that causes the error (see line 33):
    (Using the .net symbols from the PropertyGridView.cs file)
    1
            internal bool CommitValue(GridEntry ipeCur, object value) {   
    2
    3
                Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose,  "PropertyGridView:CommitValue(" + (value==null ? "null" :value.ToString()) + ")");   
    4
    5
                int propCount = ipeCur.ChildCount;  
    6
                bool capture = Edit.HookMouseDown;  
    7
                object originalValue = null;   
    8
    9
                try {   
    10
                    originalValue = ipeCur.PropertyValue;   
    11
    12
                catch {   
    13
                    // if the getter is failing, we still want to let  
    14
                    // the set happen.  
    15
    16
    17
                try {  
    18
                    try {   
    19
                        SetFlag(FlagInPropertySet, true);   
    20
    21
                        //if this propentry is enumerable, then once a value is selected from the editor,   
    22
                        //we'll want to close the drop down (like true/false).  Otherwise, if we're  
    23
                        //working with Anchor for ex., then we should be able to select different values  
    24
                        //from the editor, without having it close every time.  
    25
                        if (ipeCur != null &&   
    26
                            ipeCur.Enumerable) {  
    27
                               CloseDropDown();   
    28
    29
    30
                        try {   
    31
                            Edit.DisableMouseHook = true;  
    32
    /*** This Step fails because the commit method is trying to convert a string to myCustom objet ***/ 
    33
                            ipeCur.PropertyValue = value;   
    34
    35
                        finally {   
    36
                            Edit.DisableMouseHook = false;  
    37
                            Edit.HookMouseDown = capture;   
    38
    39
    40
                    catch (Exception ex) {   
    41
                        SetCommitError(ERROR_THROWN);  
    42
                        ShowInvalidMessage(ipeCur.PropertyLabel, value, ex);  
    43
                        return false;  
    44
    I'm stuck.
    I was wondering is there a way to work around this? Maybe extend the string converter class to accept this?
    Thanks in advance,
    Eric

     
    Hi,
    Thank you for your post!  I would suggest posting your question in one of the MS Forums,
     MSDN Forums » Windows Forms » Windows Forms General
     located here:http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=8&SiteID=1.
    Have a great day!

  • How do I know if I can convert a String value to an int value or not?

    Hi,
    I want to know how to make the judgment that if I can convert a String value to an int value or not? Assume that I don't know the String is number or letters
    Thank you

    Encephalopathic wrote
    Again, why?One of the problems (have been dued) in my codelab asks us to write a class as follow
    Write a class definition of a class named 'Value' with the following:
    a constructor accepting a single integer paramter
    a constructor with no parameters
    a method 'setVal' that accepts a single parameter,
    a boolean method, 'wasModified' that returns true if setVal was ever called for the object.
    a method 'getVal' that returns an integer value as follows: if setVal has ever been called, it getVal returns the last value passed to setVal. Otherwise if the "single int parameter" constructor was used to create the object, getVal returns the value passed to that constructor. Otherwise getVal returns 0.
    The setVal(int y) returns nothing, so how do I know whether it has been called or not?
    Thank you

  • Looking for a simple way to convert a string to title case

    New to LiveCycle and Javascript.  Looking for a simple way to convert a string to title case, except acronyms.  Currently using the the following, it converts acronyms to lower case:
    var str  =  this.rawValue;
    var upCase = str.split(" ");
    for(i=0; i < upCase.length; i++) {
    upCase[i] = upCase[i].substr(0,1).toUpperCase() + upCase[i].substr(1).toLowerCase();
    this.rawValue = upCase.join(' ');

    Thanks for the reply.
    Found the following script in a forum, which works fine as a "custom validation script" in the.pdf version of my form.  However, it will not work in LiveCycle?  The problem seems to be with
    "return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g"
    function toTitleCase(str) {
    var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
        return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function(match, index, title){
    if (index > 0 && index + match.length !== title.length &&
      match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
    (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
    title.charAt(index - 1).search(/[^\s-]/) < 0) {
    return match.toLowerCase();
    if (match.substr(1).search(/[A-Z]|\../) > -1) {
      return match;
      return match.charAt(0).toUpperCase() + match.substr(1);
    event.value = toTitleCase(event.value);

  • Convert a String to Decimal Format in European format

    Hi Experts,
    I am having a string as a context type for a input field, where the user can enter the Price, I need to convert the same into European format "###.###,00", I am using this below code to convert the string to decimal format
    User will enter the input as 10 as it needs to be converted into 10,00. Also, 1000 which has to be converted as 1.000,00
    String Str1 = wdContext.currentvn_temptable.getVa_TempUnitPrice();
    Locale mylocale  = Locale.GERMAN;
    String pattern="###.###,00";                    
    NumberFormat nf = NumberFormat.getNumberInstance(mylocale);
    DecimalFormat df = (DecimalFormat)nf;
    df.applyPattern(pattern);
    String output = df.format(Str1);
    wdComponentAPI.getMessageManager().reportSuccess("Unit Price" + " " + pattern + " " + output);
    When I execute the above code, i am getting an error called "Malformed Pattern ###.###,00"
    Please let me know, how to convert a String to Quantity in European format
    Thanks & Regards,
    Palani

    Hello!
    Try to change your pattern to this one 
    Locale mylocale  = Locale.GERMAN;
    String pattern = "#,#00.00";                    
    NumberFormat nf = NumberFormat.getNumberInstance(mylocale);
    DecimalFormat df = (DecimalFormat)nf;
    df.applyPattern(pattern);
    String output = df.format(1111111.222);
    Pattern has an influence on number of digits between separators, but you have to use ',' for grouping and '.' for decimal. Character values for separators correspond to your Locale object.
    Thanks, Mikhail

  • How to convert a string value to date

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    In your post you ask how to convert a string value to a date.  The value returned from the Get-AdUser is already a date.  It does not need to be converted.
    Bill has sshown one way to convert a date to a string and there are other methods.  You need to clarify your question.
    If you are really trying ot convert strings to dates then you can start with this:
    [datetime]'01/21/1965 13:33:23'
    Most date strings aer autodetected by the class.
    ¯\_(ツ)_/¯

  • Error synchroniz​ing with Windows 7 Contacts: "CRADSData​base ERROR (5211): There is an error converting Unicode string to or from code page string"

    CRADSDatabase ERROR (5211): There is an error converting Unicode string to or from code page string
    Device          Blackberry Z10
    Sw release  10.2.1.2977
    OS Version  10.2.1.3247
    The problem is known by Blackberry but they didn't make a little effort to solve this problem and they wonder why nobody buy Blackberry. I come from Android platform and I regret buying Blackberry: call problems(I sent it to service because the people that I was talking with couldn't hear me), jack problems (the headphones does not work; I will send it again to service). This synchronisation problem is "the drop that fills the glass". Please don't buy Blackberry any more.
    http://btsc.webapps.blackberry.com/btsc/viewdocume​nt.do?noCount=true&externalId=KB33098&sliceId=2&di​...

    This is a Windows registry issue, if you search the Web using these keywords:
    "how to fix craddatabase error 5211"       you will find a registry editor that syas it can fix this issue.

  • How to convert a String("yyyy-mm-dd") to the same but in Date format ?

    Hi,
    can anyone plz tell me how to convert a String to a date format.I'm using MSACCESS database.I want to store this string in the database.So i need to convert it to a date format since the table is designed such a way with date/time type for date field.I used SimpleDateFormat ,but i can't able to convert.The code is given below:
    coding:
    public String dateconvertion(String strDate)
    try
    SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdfSource.parse(strDate);
    SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd ");
    strDate = sdfDestination.format(date);
    catch(ParseException pe)
    System.out.println("Parse Exception : " + pe);
    return(strDate);
    }

    i used prepared statement even now i am getting error like this.....
    i have included the prepared statement package also...
    my coding:
    ResultSet rsdatetemp = null;
    PreparedStatement ps = null;
    String query ="select distinct itemcode from sales where bill date between ? and ?";
    ps = precon.prepareStatement(query);
    ps.setDate(1,d1);//d1 and d2 are in date format
    ps.setDate(2,d2);
    rsdatetemp = ps.executeQuery();
    error :
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(1,d1);
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(2,d2);

Maybe you are looking for

  • File to BAPI error

    hi, iam getting following error in file to bapi scenario.plz help me 2007-11-02 17:21:20     Success     RFC adapter received a synchronous message. Attempting to send sRFC for BAPI_SALESORDER_CREATEFROMDAT1 2007-11-02 17:21:21     Error     Exceptio

  • ITunes crash every time I tried to launch it

    I've updatet to the 10.5 iTunes and it worked properly, but after few days it just stoped launching. every time the same error OS Version:      Mac OS X 10.7.2 (11C74) Report Version:  9 Interval Since Last Report:          52955 sec Crashes Since La

  • How to download updates for sun creator to install them offline

    I have creator installed machine. I want to update it but it does not have internet connection, so I want to install updates in another machine and install them in this offline machine from where I can download upadates any ideas?

  • Output type configured as "CanNotChanged" (NACE) and process mode 2 in VF31

    When we configure a billing document output type as "CanNotChanged" (NACE), we can no longer use the processing mode 2 in the VF31 transaction to repeat the printing of the documents which have been printed allready once.

  • P7N Diamond v1.0

    Hi all, It's been a while I'm trying to find out what is happening here, I have: P7N Diamond Q9650 @3.0GHz Corsair CM2X2048-6400C5 (2Gbx2) MSI 8800GTS x 2 The first time I assembly the computer I got stacked at the middle of POST, but it was a BIOS i