0

I have checked a number of posts and regex examples but for some reason I can't get the leading 0's to be removed from the date string below. Can anyone see what I am doing wrong?

wanted result: 4/6/2022

What I have tried:

String shipDate = '04/06/2022';
String shipDate2 = '04/06/2022';
String shipDate3 = '04/06/2022';
String shipDate4 = '04/06/2022';
system.debug('1::: ' + shipDate.replaceFirst('^0+', ''));
system.debug('2::: ' + shipDate2.replaceFirst('^0+(?!$)', ''));
system.debug('3::: ' + shipDate3.replaceAll('/\b0/g', ''));
system.debug('4::: ' + shipDate4.replaceFirst('\b0/g', ''));

I have tried all of these suggestions: https://stackoverflow.com/questions/8897298/remove-leading-zeroes-in-datestring and can see here https://regex101.com/ that the \b0 works...is there something with apex that doesn't like regex expressions formatted like this?

2
  • 1
    This is an X-Y Problem. Why do you want to remove the zeroes (what is your X)?
    – sfdcfox
    Apr 13 at 18:52
  • Why do you want to remove the leading zeros? Also, why aren't you using ISO 8601 date format here? YYYY-MM-DD helps keep things unambiguous.
    – Derek F
    Apr 13 at 18:56

2 Answers 2

2

If you really want a locally formatted date, you can use Date.parse and Date.format:

String shipDate = '04/06/2022';
System.debug(Date.parse(shipDate).format());

However, be aware that Date.parse depends on the user locale, and the format method also depends on the user locale. In other words, this answer will only work if the date is formatted in the correct locale for the user.


A more literal interpretation, we can split, format, and join, like this:

String shipDate = '04/06/2022';
String[] values = shipDate.split('/');
for(Integer i = 0; i < values.size(); i++) {
    values[i] = Integer.valueOf(values[i])+'';
}
System.debug(String.join(values,'/'));

For a Regular Expression approach, you can use:

String shipDate = '04/06/2022';
// Option 1:
shipDate = shipDate.replaceAll('\\b0(\\d)','$1');
// Option 2:
shipDate = shipDate.replaceAll('\\b0','');
System.debug(shipDate);

Note that if a Regular Expression wants an escaped character, such as \b or \d, you need to escape it again, because that's also Apex's escape character. This is why you see \\b and \\d in the example above.

Also note that Apex's Regular Expression format is closer to Java, not JavaScript, so /.../g doesn't actually do a global search, but just tries to match those characters. To enable the "g" flag, you have to do something like '(?g)\\b0' instead. Regardless, you don't need to, because replaceAll implies g.

You'll want to read Java's Pattern documentation for more information.

0

The formatting of date is best done via DateTime.format(...):

Converts the date to the specified time zone and returns the converted date as a string using the supplied Java simple date format.

Unfortunately converting a String such as 04/06/2022 into DateTime runs into a problem: neither Date nor DateTime support arbitrary formats for parsing. They assume you'll present a String in the current user's locale. While this is certainly doable for a well-known, fixed locale, in a more general case this becomes cumbersome. JSON to the rescue!

In JSON, the date/time format is not standardized...but it is standardized in JavaScript via ISO 8601. Many JSON implementations follow the "JSON is JavaScript" dogma and adopt ISO 8601 format as a best practice/convention:

Date: 2022-04-13 Date and time in UTC:

  • 2022-04-13T18:26:19+00:00
  • 2022-04-13T18:26:19Z
  • 20220413T182619Z

Salesforce's JSON serialization/deserialization engine happens to use ISO 8601. The timezone does matter when you're dealing with string/date conversion. If you omit the timezone, results can be confusing. This example does everything in GMT:

String shipDate = '04/06/2022'; // assume GMT
String[] shipDate_parts = shipDate.split('/');
String shipDate_iso8601 = String.format(
    '{0}-{1}-{2}T00:00:00Z', // YYYY-MM-DD:..
    new List <Object> {
        shipDate_parts[2],
        shipDate_parts[0],
        shipDate_parts[1]
    });

DateTime dt = (DateTime) JSON.deserialize('"' + shipDate_iso8601 + '"', DateTime.class);
String shipDateWithoutZeros = dt.format('M/d/yyyy', 'GMT');

System.debug(shipDate + ' -> ' + dt + ' -> ' + shipDateWithoutZeros);

prints

04/06/2022 -> 2022-04-06 00:00:00 -> 4/6/2022

to the debug log

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.