we can use the java.text.SimpleDateFormat class. First, create a Date
object. Next, create a SimpleDateFormat instance using the getDateInstance(SimpleDateFormat.SHORT) method. Next, create a String representing the Date without a timestamp with the format method. Finally, create a new Date object using the SimpleDateFormat instance's parse method and passing it the date String.
Remove Timestamp from Date in Java - Example Code
import java.text.DateFormat;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
// The following example code demonstrates how to
// remove the timestamp from a Date object.
public class RemoveTimestampFromDate {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date.toString());
DateFormat df = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);
String dateString = df.format(date);
try {
Date dateWithoutTimestamp = df.parse(dateString);
System.out.println(dateWithoutTimestamp.toString());
} catch (ParseException e) {
}
}
}
Here is the output of the example code:
Sun Apr 17 10:44:43 CEST 2011 Sun Apr 17 00:00:00 CEST 2011
No comments:
Post a Comment