Wednesday, 17 January 2018

System.Today() Vs System.Now() in Apex (Salesforce) and Change the Date Format Style

Difference between System.Today() & System.Now ?

***** System.Today() *******

1. The return type of System.Today() is Date, so you can't store it in other data types like- integer, string, etc.
    i.e. - Date date1 = System.Today();

2. Return only the Date but not the time, if you debug the upper code then you will find it.
    i.e. 2018-01-16 00:00:00

***** System.Now() *******
1. The return type of System.Now() is DateTime, so you can't also store it in other data types like- integer, string, etc as well as System.Today().
    i.e. - DateTime date1 = System.Today();

2. Return both Date and Time, if you debug the upper code then you will find them.
    i.e. - 2018-01-16 10:17:23

REMEMBER - 
    If you can code this by mistake where the return type is Date of  DateTime then you will get the error.
    i.e. - Date date1 = System.Now();

Result - ErrorIllegal assignment from Datetime to Date

Because the Now() function always returns Date, the same as the Today() function always returns Date and Time both. In a real-world example, if you can accept 5 characters then you can never store more than 5 characters (the same concept is here).


********** Change the Date Format Style *************

String date1 = system.today().month()+'/'+system.today().day()+'/'+system.today().year();
system.debug(date1);

Result - 1/16/2018

Datetime Date1= Datetime.now();
// Change the format of your date and store in a String Data Type using '.format'.
String dateOutput = Date1.format('MMM/dd/yyyy');
system.debug(dateOutput);

Result Jan/16/2018


You can also change the date format as you want



// MM = Month, DD =  Date, YYYY = Year
String dateOutput = Date1.format('MM/dd/yyyy');

Result 01/16/2018

String dateOutput = Date1.format('MM-dd-yyyy');

Result 01-16-2018

String dateOutput = Date1.format('MM,dd,yyyy');

Result 01,16,2018

// Date  Month  Year
String dateOutput = Date1.format('dd/MM/yyyy');

Result 16/01/2018

Result Of Date Formats -




No comments:

Post a Comment

Total Pageviews