0

My current code to display the date is a bit long. I'd like to shorten it to show less.

What it displays: Sun May 18 20:36:30 MTS 2019

What I want: May 18

public void giveDays(int days) {
   if (memberTill < Utils.currentTimeMillis())
      memberTill = Utils.currentTimeMillis();
      Date date = new Date(memberTill);
      date.setDate(date.getDate() + days);
      memberTill = date.getTime();
}
public String getEndingDate() {
return "Ends: " + new Date(membershipTill);
}
Philip Wrage
  • 1,505
  • 1
  • 12
  • 23
  • Refer below question for more information on date formats https://stackoverflow.com/questions/4772425/change-date-format-in-a-java-string – ASP May 19 '19 at 05:23
  • 1
    I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). And `DateTimeFormatter` for formatting it into `May 18`. – Ole V.V. May 19 '19 at 06:10

2 Answers2

2

You can achieve it using DateTimeFormatter (introduced in Java 8 DateTime API). DateTimeFormatter is a replacement for the old SimpleDateFormat and it is thread-safe:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterDemo {
    public static void main(String args[]) {
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd");
        String text = date.format(formatter);
        System.out.println("text:" + text);
    }
}
mukesh210
  • 2,792
  • 2
  • 19
  • 41
1

You are looking for SimpleDateFormat in java

import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("MMM dd");
    String strDate= formatter.format(date);
    System.out.println(strDate);
}
}
karthikdivi
  • 3,466
  • 5
  • 27
  • 46
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. May 19 '19 at 06:10
  • @OleV.V. , You are right upto some extend but user might be using Java version less than 8. Actually while answering we should be providing all the possible ways to do it with pros and cons. – Piyush N May 19 '19 at 06:19
  • For Java 6 and 7 I’d recommend [the baclport of java.time](https://www.threeten.org/threetenbp/). If you want to provide an answer for Java 5, or for Java 6 and 7 without any external dependency, very fine, only please make explicit that that is what you are doing. – Ole V.V. May 19 '19 at 06:26