How to Convert the Date from One Format to Another Date Object in Another Format Without Using Any Deprecated Classes

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Use SimpleDateFormat#format:

DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821

Also note that parse takes a String, not a Date object, which is already parsed.

convert date from one format to another in java

Avoid old date-item classes

You are using outmoded old date-time classes bundled with the earliest versions of Java. They have proven to be poorly designed, confusing, and troublesome. Avoid them.

java.time

Java 8 and later comes with the java.time framework built-in. A vast improvement!

In java.time, an Instant is a moment on the timeline in UTC.

Your input string complies with the ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating string representations of their date-time values. So no need to specify a formatting pattern. The Instant class can directly parse such a string.

String input = "2016-03-09T06:00:53.0Z";
Instant instant = Instant.parse ( input );

An Instant is only intended as a basic building block. So for generating formatted strings we must convert to an OffsetDateTime object. You apparently want the same time zone of UTC, so we specify the constant ZoneOffset.UTC.

OffsetDateTime odt = OffsetDateTime.ofInstant ( instant , ZoneOffset.UTC );

We define a DateTimeFormatter to use your pattern. The reader should note the desired pattern uses the uppercase-D DDD pattern which means day-of-year (a count between 1 and 365/366).

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "yyyyDDDHHmmssSSS" );
String output = odt.format ( formatter );

Dump to console.

System.out.println ( "input: " + input + " = instant: " + instant + " = odt: " + odt + " = output: " + output );

When run.

input: 2016-03-09T06:00:53.0Z = instant: 2016-03-09T06:00:53Z = odt: 2016-03-09T06:00:53Z = output: 2016069060053000

Caution: I strongly recommend against generating such strings lacking any offset-from-UTC or time zone information. That is as unwise as transmitting a currency amount without noting which currency (USD, CAD, MXN, etc.).

Such serializations of date-time values to strings should stick to the sensible and intuitive formats defined by ISO 8601 whenever possible.

How can I get the year from a Date object without using deprecated methods?

I can think of three ways to obtain the year from a Date object but avoiding the deprecated methods. Two of the approaches use other Objects (Calendar and SimpleDateFormat), and the third parses the .toString() of the Date object (and that method is not deprecated). The .toString() is potentially locale specific, and there could be issues with the approach in other locales, but I am going to assume (famous last words) that the year is always the only sequence of 4 digits. One could also understand the specific locale and use other parsing approaches. For example, standard US/English puts the year at the end (e.g., "Tue Mar 04 19:20:17 MST 2014"), one could use the .lastIndexOf(" ") on the .toString().

/**
* Obtains the year by converting the date .toString() and
* finding the year by a regular expression; works by assuming that
* no matter what the locale, only the year will have 4 digits
*/
public static String getYearByRegEx(Date dte) throws IllegalArgumentException
{
String year = "";

if (dte == null) {
throw new IllegalArgumentException("Null date!");
}

// match only a 4 digit year
Pattern yearPat = Pattern.compile("^.*([\\d]{4}).*$");

// convert the date to its String representation; could pass
// this directly, but I prefer the intermediary variable for
// potential debugging
String localDate = dte.toString();

// obtain a matcher, and then see if we have the expected value
Matcher match = yearPat.matcher(localDate);
if (match.matches() && match.groupCount() == 1) {
year = match.group(1);
}

return year;
}

/**
* Constructs a Calendar object, and then obtains the year
* by using the Calendar.get(...) method for the year.
*/
public static String getYearFromCalendar(Date dte) throws IllegalArgumentException
{
String year = "";

if (dte == null) {
throw new IllegalArgumentException("Null date!");
}

// get a Calendar
Calendar cal = Calendar.getInstance();

// set the Calendar to the specific date; the reason why
// Calendar is deprecated is this mutability
cal.setTime(dte);

// get the year using the .get method, and convert to a String
year = String.valueOf(cal.get(Calendar.YEAR));

return year;
}

/**
* Uses the SimpleDateFormat with a format for only a year.
*/
public static String getYearByFormatting(Date dte)
throws IllegalArgumentException
{
String year = "";

if (dte == null) {
throw new IllegalArgumentException("Null date!");
}

// set a format only for the year
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

// format the date; the result is the year
year = sdf.format(dte);

return year;
}

public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
cal.set(2014,
Calendar.MARCH,
04);

Date dte = cal.getTime();

System.out.println("byRegex: "+ getYearByRegEx(dte));
System.out.println("from Calendar: "+ getYearFromCalendar(dte));
System.out.println("from format: " + getYearByFormatting(dte));
}

All three approaches return the expected output based upon the test input.

Is there a way to copy Date object into another date Object without using a reference?

You could use getTime() and passing it into the Date(time) constructor. This is only required because Date is mutable.

Date original = new Date();
Date copy = new Date(original.getTime());

If you're using Java 8 try using the new java.time API which uses immutable objects. So no need to copy/clone.

Java unparsable date SimpleDateFormat

Date format should be

EEE MMM dd HH:mm:ss z yyyy

Your code works fine using this format.

using java.time API

LocalDate.parse(datestr, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy")).format("TO DATE PATTERN");

Further details at Using java.time package to format date



Related Topics



Leave a reply



Submit