Hot answers tagged

60

Formulas There isn't a built-in function to do this for you, but you... UPDATE: As of Spring 2018, there's a built-in function for this: WEEKDAY(). It returns an integer where 1 is Sunday, 2 is Monday, 3 is Tuesday, etc. Apex Code You could do the same thing with time deltas, but you can also use the poorly documented DateTime.format() function: // Cast ...


31

You can use the getTime method to get the milliseconds between them and then convert to whatever unit you need: Long dt1Long = DateTime.now().addDays(-1).getTime(); Long dt2Long = DateTime.now().getTime(); Long milliseconds = dt2Long - dt1Long; Long seconds = milliseconds / 1000; Long minutes = seconds / 60; Long hours = minutes / 60; Long days = hours / 24;...


30

Just use addDays with a negative value: Date.today().addDays(-1)


21

Another alternative that avoids the pitfalls of format() returning locale specific values is to use the daysBetween() function between a known date and the comparison. (This is the apex equivalent to your formula) For example the 1st Jan 1900 is a Monday, so the following code will give you the day of the week index with Monday being 0. Math.mod(monday....


19

Datetime objects have this date method: date() Returns the Date component of a Datetime in the local time zone of the context user. so your code can use it like this: Datetime dt = (Datetime) resultSet.get('LastModifiedDate'); sf.lastModifiedDate = dt.date(); (Generally you would need a null check in the code but as LastModifiedDate always has a ...


17

You can use the addDays() functions as already mentioned, but SOQL has a Date Literal Already set up for this, and might be a bit more simple. You just simply have to query for a date of YESTERDAY An example list<Account> accounts = [Select Id From Account Where CreatedDate = YESTERDAY]; Here is the documentation for Date Literals. Although the ...


17

This should work for records from two months ago (i.e. - Today is 25th September, that means 1st July - 31st July): WHERE CreatedDate = LAST_N_MONTHS:2 AND CreatedDate < LAST_N_MONTHS:1 And the second query for records from 13 months ago, which is the previous month of last year (i.e. - Today is 25th Sep. 2016, so this will return 1st August - 31st ...


16

Actually... the datetime format is right. The capital Y merge field is the WEEK YEAR - which from the 27th December 2015 is IN 2016! The lower case y merge field is the CALENDAR YEAR - which will be 2015 as expected. Change your line to System.debug('~~~~~localDateTime'+localDateTime.format('MM/dd/yyyy')); and you will see your logs play properly. ...


16

They give you the same data. Their descriptions are almost verbatim as well: System.now() Returns the current date and time in the GMT time zone. Datetime.now() Returns the current Datetime based on a GMT calendar. And for today they are indeed verbatim: System.today() Returns the current date in the current user's time zone. Date....


15

In contradiction to what the current documentation claims, you can observe that the LAST_N_DAYS date literal includes today's data. To be sure, I ran this query: SELECT CreatedDate FROM MyObject__c WHERE CreatedDate = LAST_N_DAYS:1 ORDER BY CreatedDate DESC LIMIT 1 And I got back: 2017-08-31T18:16:17.000+0000


14

This is known as a "Unix Timestamp" (number of milliseconds since January 1st, 1970, 00:00:00 GMT). In Apex Code, you can use DateTime.newInstance(unixTimestamp) to return a DateTime that contains the formatted date/time value. In JavaScript, use new Date(unitTimestamp) to get the same result. To convert back, in Apex Code, use myDate.getTime(), and in ...


14

Date.newInstance actually seems to behave as follows: public class Date { public static Date newInstance(Integer year, Integer month, Integer day) { Date d = new Date(1, 1, 1); d.addYears(year-1); d.addMonths(month-1); d.addDays(day-1); return d; } } Curiously, year cannot be negative, so it has the net ...


14

The addDays method does not modify the value but instead returns the modified date. So you need: currentDay = currentDay.addDays(1); Your current code hits the CPU limit because currentDay never changes.


13

You can make it a fair bit more elegant and clear (not to mention one-lining it) by leveraging the Date.toStartOfMonth method. public static Date getEndOfLastMonth(Date input) { return input.toStartOfMonth().addDays(-1); }


12

This error is coming as system is not able to understand Test123 while parsing into date. The format of the String depends on the local date format, like mm/dd/yyyy. If the parameter is not of this format, date.parse will throw error. E.g.: r.Plan_Date__c = date.parse('12/27/2015'); You can also use date.valueOf(strDate) to parse string of format yyyy-MM-...


12

You can do this using Apex' Date class: acc.effectiveDate__c = Date.newInstance(2016, 12, 9); For more information check out the documentation: Apex Developer Guide - Date Class


11

You can accomplish this by using the format below <apex:outputText value="{0,date,MMMM dd, yyyy}"> <apex:param value="{!TODAY()}" /> </apex:outputText> Here is the supporting documentation for formatting dates with output text http://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_outputText.htm And here is some ...


11

Create a "Birthday Notification Date" field. Create a Workflow with a Workflow Field Update that checks for an entered birthday and updates the Birthday Notification Date field with the correct value. Create a Time Based Workflow rule that fires on the Birthday Notification Date field, sends the email, and clears the field. Make sure that "recursive mode" ...


11

Using the example given in the DateTime class and calling the formatGMT(string) method with a formatting string found in the Java SimpleDateFormat examples: DateTime myDateTime = DateTime.newInstance(1993, 6, 6, 3, 3, 3); String formatted = myDateTime.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ'); system.debug(formatted); Produces this result: 15:41:47:003 ...


10

Have you tried Date.parse()? From the documentation: Constructs a Date from a String. The format of the String depends on the local date format. The following example works in some locales: date mydate = date.parse('12/27/2009');


10

Since Apex uses Java's SimpleDateFormat, you can get the full name of the day of the week. Date d = System.today(); Datetime dt = (DateTime)d; String dayOfWeek = dt.format('EEEE'); //This returns - Monday, Tuesday, Wednesday, etc.. Basically the same apex code as @Benj provided except the format part. For a full list of supported formats, check [...


10

I think the simplest method for you to use will be something like the following: Integer d = Due_Date__c.day(); Integer mo = Due_Date__c.month(); Integer yr = Due_Date__c.year(); DateTime DT = DateTime.newInstance(yr, mo, d); If you want to keep the 11:59:59 in your local time zone, change the last line as follows: DateTime DT = DateTime.newInstance(yr, ...


10

Historically, only the System methods were originally available (System.now and System.today). The newer methods were added later, presumably because people felt it was logical that you'd find the current date in a class called Date, and the current time in a class called DateTime. They are exactly identical in behavior, so feel free to use whichever you ...


9

Date.newInstance does not accept strings, it accepts integers according to the documentation. You are passing in Strings. You could possibly try the Date.parse method.


9

The most simple way to convert a date to a date time, with a time component of 00:00:00.0, is to simply assign a Date to a Datetime variable, or to cast a Date to a Datetime. For example, the following works: Date today = Date.today(); Datetime todayDateTime = today; // Implicit cast System.debug('Today is ' + todayDateTime); System.debug('Today is also ' + ...


9

All formula fields are calculated at run time. No value is stored on the record for a formula field. This means that any time you view a record, either through the UI or a report, the formula is calculated at the time you run it. In short, yes.


9

Attribution Use: system.debug(Datetime.now().formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'')); The esteemed Mr Ballinger also recommends the following, but it is wrapped in double quotes and slower, so I would probably not use it, myself. system.debug(JSON.serialize(Datetime.now()));


9

Neither formula will be perfectly correct. Depending on your tolerance, you might consider: (date1 - date2) / 30.43685 This gives you the number of days divided by the number of average days in a month in an average year. I derived this value from 365.2422, the number of "sol days", divided by the number of calendar months, 12. If you're looking for a ...


9

You can get the Date value from a Datetime instance by calling the date() method: obj2.Date__c = obj1.CreatedDate.date(); If you're calling this method on a Datetime instance where you are not sure if it can be null, make sure to add a null check: obj2.Date__c = (obj1.CreatedDate == null) ? null : obj1.CreatedDate.date();


9

I'm afraid you won't be able to do it. As @itzmukeshy7 said, the way to go is to pass the Date as a String and then cast it inside your Apex method. There are several issues like this currently in the framework, I've published a blog post to try to list them and their related workaround, you can have a look here if you're interested. I would suggest that ...


Only top voted, non community-wiki answers of a minimum length are eligible