I have to fetch date of last Thursday of month of any year but the problem I'm facing is that for the month of dec'15 last thursday is 31-dec-2015 but I'm getting 24-dec-2015 for the following code:    Date getLastThursday(def month, def year ) {     Calendar cal = Calendar.getInstance();     cal.set( year, month,1 )     cal.add( Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )%7+2) );     return cal.getTime(); }   And also explain me how this line of code internally works?  cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK )%7+2))
15186
I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month.  I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:      for (int month = 0; month &lt; 13; month++) {         GregorianCalendar d = new GregorianCalendar();         d.set(d.MONTH, month);         System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));         d.set(d.DAY_OF_WEEK, d.FRIDAY);         d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));         while (d.get(d.MONTH) &gt; month || d.get(d.MONTH) &lt; month) {             d.add(d.WEEK_OF_MONTH, -1);         }         Date dt = d.getTime();         System.out.println("Last Friday of Last Week in  " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());     }
5931
In java.util.Calendar, January is defined as month 0, not month 1. Is there any specific reason to that ?  I have seen many people getting confused about that...
41793
I have a child table that is something like this:  [Cust Date Table]  | Customer ID | Some Date  | Balance | +-------------+------------+---------+ |           1 | 2012-04-30 |   20.00 | |           1 | 2012-03-31 |   50.00 | |           2 | 2012-04-30 |    0.00 | |           2 | 2012-03-31 |   10.00 |  |           3 | 2012-03-31 |   60.00 | |           3 | 2012-02-29 |   10.00 |   I would like to be able to get a result set like this - one record for each client with the latest date:  | Customer ID | Some Date  | Balance | +-------------+------------+---------+ |           1 | 2012-04-30 |   20.00 |  |           2 | 2012-04-30 |    0.00 | |           3 | 2012-03-31 |   60.00 |   I know that I can do this for each individual "Customer ID" with the following SQL (SQL Server syntax):  select top 1  [Some Date], [Customer ID], [Balance] from [Cust Date Table] where [Customer ID] = 2 order by [Some Date] desc   | Customer ID | Some Date  | Balance | +-------------+------------+---------+ |           2 | 2012-04-30 |    0.00 |   But I'm not sure how to get all three of the records I want.  I'm not sure if this is a situation that calls for a sub-query or something else.    Please note that the max date can be different for any given [Customer ID], (in this example, customer 3's maximum date is 2012-03-31 whereas the other records have a max date of 2012-04-30). I have tried  select [Customer ID], MAX([Some Date]) AS [Latest Date], Balance  from [Cust Date Table]  group by [Customer ID], Balance;    The problem is this doesn't return just the one row for each customer - it returns multiple rows.
68732
I am using the jQuery Datepicker widget with two input boxes, one for the "From" date and the second with the "To" date. I am using the  as a basis for getting the two input boxes to work with each other, but I need to be able to add these additional restrictions:   Date range can be no earlier than 01 December 2008  "To" date can be no     later than today Once a "From" date     is selected, the "To" date can only     be within a range of 7 days after     the "From" date If a "To" date is     selected first, then the "From" date     can only be within the range of 7     days before the "To" date (with the     limit of 01 December being the first     selectable date)   I can't seem to get all of the above working together.  In summary, I would like to be able to select a range of up to 7 days between 01 December and today (I realise I am posting this on 1st December so will only get today for the moment).  My code so far  $(function () {  $('#txtStartDate, #txtEndDate').datepicker(             {             showOn: "both",             beforeShow: customRange,             dateFormat: "dd M yy",             firstDay: 1,              changeFirstDay: false             }); });  function customRange(input)  {   return {          minDate: (input.id == "txtStartDate" ? new Date(2008, 12 - 1, 1) : null),          minDate: (input.id == "txtEndDate" ? $("#txtStartDate").datepicker("getDate") : null),           maxDate: (input.id == "txtStartDate" ? $("#txtEndDate").datepicker("getDate") : null)        };  }   I'm missing the 7 day range restriction and also preventing a "To" date selection before 01 December 2008 or after today. Any help would be much appreciated, Thanks.
91716
I have a year's worth of inventory data, and I want to extract the first and last day of each month's data. What is the best way to do this?
13653
How do I get timestamp from e.g. 22-09-2008?
63275
I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to Date.toMonth(), Date.toYear() and other deprecated Date methods.  All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying they might go away any day now and he should use Calendar methods.  Has Sun/Oracle actually said when these things are going away, or does @deprecated just mean you lose style points?
52755
I need to get the current time but to be in type DateTime. I use:  DateTime now = System.now();   but it returns wrong time. I execute the code in 2017-08-04 00:38:46 AM but it returns     00:38:46:023 USER_DEBUG [138]|DEBUG|now 2017-08-03 21:38:46   How can I get my correct current local time 2017-08-04 00:38:46?  I had even tried with:  DateTime now = DateTime.parse(System.Now().format());   but I still get wrong time.     01:10:09:021 USER_DEBUG [139]|DEBUG|now 2017-08-03 22:10:00   How can I get the correct current local time?
107180
I found a great article on color coding a list item based on dates.  However, this only works for 2 days within submission.  I am trying to have a coding structure that will let me know when something is late.  This is the information I am using:   I have a column that subtracts the two dates, then I have another column that uses this script:   ="&lt;DIV style='font-weight:bold; font-size:24px; color:"&amp;CHOOSE((IF(SubmissionDateDifference&lt;=2,2,1)),"red","green","orange")&amp;";'&gt;•&lt;/DIV&gt;"   With this script, it is only given me the Red and Green colors depending on if the date is greater than 2 days or less than 2 days.  I would like to have it give me Red for 0 days and green for greater than 0.  When I tried to change the numbers to &lt;=0,0, the formula didn't work.  Also, the final piece in case you were wondering is setting up a web part with the list and below the list is a CEWP with this HTML Script:  &lt;script type="text/javascript"&gt; // // Text to HTML // Demo: sharepoint.infoyen.com by Avinash Kumar Dad // var cellTDs = document.getElementsByTagName("TD"); var i=0; var TDContent = " "; while (i &lt; cellTDs.length) { try { TDContent = cellTDs[i].innerText || cellTDs[i].textContent; if ((TDContent.indexOf("&lt;DIV") == 0) &amp;&amp; (TDContent.indexOf("&lt;/DIV&gt;") &gt;= 0)) { cellTDs[i].innerHTML = TDContent; } } catch(err){} i=i+1; } // // ExpGroupRenderData overwrites the default SharePoint function // This part is needed for collapsed groupings // function ExpGroupRenderData(htmlToRender, groupName, isLoaded) {    var tbody=document.getElementById("tbod"+groupName+"_");    var wrapDiv=document.createElement("DIV");    wrapDiv.innerHTML="&lt;TABLE&gt;&lt;TBODY id=\"tbod"+ groupName+"_\" isLoaded=\""+isLoaded+ "\"&gt;"+htmlToRender+"&lt;/TBODY&gt;&lt;/TABLE&gt;";    var tBODYTDs = wrapDiv.getElementsByTagName("TD"); var j=0; var cellTDContent = " ";    while (j &lt; tBODYTDs.length) {       try {          cellTDContent = tBODYTDs[j].innerText || tBODYTDs[j].textContent;          if ((cellTDContent.indexOf("&lt;DIV") == 0) &amp;&amp; (cellTDContent.indexOf("&lt;/DIV&gt;") &gt;= 0)) {            tBODYTDs[j].innerHTML = cellTDContent;          }      }      catch(err){}      j=j+1;   }   tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody); }     The link for this assistance came from    Any assistance will be greatly appreciated.
20307
I'm not sure if this gets the past date within the current day or if it only takes 30 or 31 days to it.  e.g.  If the current date is March 28th, 1 month ago must be February 28th, but what happen when it's March 30th?  Scenario  I want to backup some files each day, the script will save this files within the current date with $(date +%Y%m%d) format, like 20150603_bckp.tar.gz, then when the next month arrives, remove all those files within 1 month ago except the 1st's and the 15th's files, so this is my condition:  past_month = $(date -d "-1 month" +%Y%m%d) day = $(date +%d) if [ "$day" != 01 ] &amp;&amp; [ "$day" != 15 ] then     rm /path/of/files/${past_month}_bckp.tar.gz     echo "Depuration done" else     echo "Keep file" fi   But I want to know, what will happen when the date is 30th, 31th or even the past February example? It will keep those files? or remove day 1st files?  When it's 31th the depuration will execute, so if the past month only had 30 days, this will remove the day 1st file?   I hope I hinted.
116559
I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly.  That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.  It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way.    What's the simplest way of doing this?  [Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
58207
I am having date field in the UI. I have written code as per below      Datetime XXX = (Datetime)FieldName;     yyy= XXX.format('yyyyMMdd');   But after executing the batch date is decremented by 1 automatically  Can anyone suggest some idea??  Thanks in advance.
122089
I try to add an item to my sharepoint list from a custom web part. Is there any mistake in my code?  [WebMethod]         public static string AjouterDemande()         {             SPList ListeDemandeConge = SPContext.Current.Site.RootWeb.Lists["DEMANDE CONGÉ"];             SPListItem ListItem = ListeDemandeConge.Items.Add();             ListItem["CODE"] = code;             ListItem["DEMANDEUR"] = Utilisateur.LoginName;             ListItem["DATE DEMANDE"] = DateTime.Today.Date;             ListItem["DATE FIN"] = EndDateD;             ListItem["DATE DEPART"] = StartDateD;             ListItem["DUREE"] = int.Parse(DayCount);             ListItem["PREMIER RESPONSABLE"] = Employe.FirstSuperior.LoginName;             ListItem["DEUXIEME RESPONSABLE"] = Employe.SecondSuperior.LoginName;             ListItem["PRESENCE PRES"] = Boolean.Parse(FirstRespPresent);             ListItem["SOLDE CONGE"] = Conge.SoldeAnneeConge;             ListItem["MOIS"] = int.Parse(StartDateTab[1]);             ListItem["ANNEE"] = int.Parse(StartDateTab[0]);             ListItem["JOURS APPROUVEES"] = 0;             ListItem.Update();             ListeDemandeConge.Update();             return "true";          }   When I use F10 to process debugging step by step and get to my listitem.update(), it went out without giving any error.
94790
Closed until Monday means, it will open at Monday.  But I contract with them until Dec 31st means the contract is valid at 31st...  Why is that?  Also, regarding Closed until Dec 31st:    Is this option not as clear as using the day of the week? Would it be clearer to say, 'Closing until end of Dec 31st'? (If I want to include that date) Would using the day of the week after make it more clear than using just the date?
67758
I have...   Date start = new Date()  ... ... ...  Date stop = new Date()   I'd like to get the years, months, days, hours, minutes and seconds ellapsed between these two dates.  --  I'll refine the question.  I just want to get the elapsed time, as an absolute measure, that is without taking into account leap years, the days of each month, etc.  Thus I think it's impossible to get the years and months elapsed, all I can get is days, hours, minutes and seconds.  More specifically I want to tell that a certain task lasted for e.g.   20 sec 13 min, 4 sec 2 h, 10 min, 2 sec 4 d, 4 h, 2 min, 2 sec   So please forgive my lack of precision.
75120
In a visual force page, I can take a date and do this...  &lt;apex:outputText value="{0,date, MMMM d,  yyyy}"&gt;     &lt;apex:param value="{!relatedTo.my_date__c}"/&gt; &lt;/apex:outputText&gt;   I want to be able to do that in Apex code.  So I want a method which takes a date and returns a certain format as a string.  I check the API:   and sorry if I am stupid but not so obvious how to do this?  Many thanks.