Radman Shiekh
Radman Shiekh

Reputation: 63

Convert Java Date from one format to another without converting it into string

I am trying to get my current system date and am formatting it into Etc/UTC and then into this "dd.MM.yyyy HH:mm z" format. The problem is this that the format function after formatting the date returns a string instead of date. Here is the code spinet below

    final Date currentDate = new Date();
    final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm z");
    dateFormatter.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
    String finalDateTime=  dateFormatter.format(currentDate);
    System.out.println(finalDateTime); 

Is there any alternative solution which allows me to format the date by keeping me within this date object because I have researched every date library after java 8 and before java 8, it seems like if I want to format any type of date or dateTime, I have to use a formatter which converts the given date into string.

Any Alternative solutions or it is not possible?

Upvotes: 1

Views: 1052

Answers (1)

Sweeper
Sweeper

Reputation: 271420

Date represents a single point in time. That's it, nothing more, nothing less. It does not contain any information about time zones.

Wed Jun 06 12:38:15 BST 2018 is the same Date (instant) as Wed Jun 06 11:38:15 GMT 2018, just in a different time zone. It's like the words "humans" and "homo sapians". They refer to the same species, they are just kind of in a different "format".

So you don't need to change the date in any way. You just need to format it differently. This is why formatters return Strings. Only Strings can represent one particular format of a date.

Upvotes: 5

Related Questions