1

need some suggestions on below requirement. Each response help a lot thanks in advance....

I have a date of type String with timestamp ex: Jan 8 2019 4:44 AM

My requirement is if the date is single digit I want date to be 1 space and digit (ex: 8) and if the date is 2 digits which is dates from 10 to 31 I want date with no space(ex:10) and also same for hour in timestamp.

to summarize: if the date is 1 to 9 and hour in timestamp is 1 to 9 looking for below string

Jan  8 2019  4:44 AM

if the date is 10 to 31 and hour in timestamp is 10 to 12 looking for below string

Jan 18 2019 12:44 AM

right now I am creating a date in following way:

val sdf = new SimpleDateFormat("MMM  d yyyy  h:mm a")

but the above format satisfies only one condition which is dates from 1 to 9.

my application is spark with scala so looking for some spark scala code or java.

I appreciate your help...

Thanks..

1
  • I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use for example LocalDateTime and DateTimeFormatter, both from java.time, the modern Java date and time API. Commented Feb 21, 2019 at 14:38

1 Answer 1

1

java.time

Use p as a pad modifier in the format pattern string. In Java syntax (sorry):

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "MMM ppd ppppu pph:mm a", Locale.ENGLISH);
    System.out.println(LocalDateTime.of(2019, Month.JANUARY, 8, 4, 44)
            .format(formatter));
    System.out.println(LocalDateTime.of(2019, Month.JANUARY, 18, 0, 44)
            .format(formatter));
Jan  8 2019  4:44 AM
Jan 18 2019 12:44 AM

And do yourself the favour: Forget everything about the SimpleDateFormat class. It is notoriously troublesome and fortunately long outdated. Use java.time, the modern Java date and time API.

Link: Oracle tutorial: Date Time explaining how to use java.time.

To quote the DateTimeFormatter class documentation:

Pad modifier: Modifies the pattern that immediately follows to be padded with spaces. The pad width is determined by the number of pattern letters. This is the same as calling DateTimeFormatterBuilder.padNext(int).

For example, 'ppH' outputs the hour-of-day padded on the left with spaces to a width of 2.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.