[SalesForce] Convert JS date to Apex format

I am calculating date in JS in the below format:

var startnew= new Date(currentYear,3*currQuarter-2,1);
var enddatenew= new Date(currentYear,3*currQuarter+1,0);

In Apex :

List<String> parts = startnew.split('T');

List<String> partstart = parts[0].split('-');

String startdate = partstart[1]+'/'+partstart[2]+'/'+partstart[0];

date startdateformat= date.parse(startdate);
List<String> parts2 = enddatenew.split('T');
List<String> partend = parts2[0].split('-');
String enddate = partend[1]+'/'+partend[2]+'/'+partend[0];
date enddateformat= date.parse(enddate);


  I want to do a SOQL  like :
select Fields__c from CustomObject__c  where   createdDate>=: startdateformat AND createdDate>=: enddateformat        

What corrections needs to be done?

Best Answer

You can simply use Date.Parse() method

parse(stringDate)

Constructs a Date from a String. The format of the String depends on the local date format.

date mydate = date.parse('12/27/2009');

In your case

Date dtStart = date.parse(startnew);
Date dtEnd = date.parse(enddatenew);

select Fields__c from CustomObject__c 
 where createdDate>=: dtStart AND createdDate>=: dtEnd        

Updates

You can also use Period object here to get the quarter start and end date.

List<Period> Dates = [Select type, StartDate, EndDate 
                       From Period WHERE type = 'Quarter' 
                        AND StartDate = THIS_FISCAL_QUARTER];
Date StartDateQuarter = Dates[0].StartDate;
Date EndDateQuarter = Dates[0].EndDate;

try like this now use

StartDateQuarter and EndDateQuarter in query
AND ( createdDate>=: quarterstartdate AND createdDate>=: quarterenddate )
Related Topic