1

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?

8
  • 3
    ...no you can't get a Date with a specific format! Commented Jun 6, 2018 at 11:30
  • What exactly do you want? Doo you want to CONVERT the date? Why not getting the information in the final output that you need? Commented Jun 6, 2018 at 11:31
  • Do you want to change the timezone? Commented Jun 6, 2018 at 11:38
  • You can change the timezone but there's no point of changing the date to me? If you need to do so , create a new date instance. Commented Jun 6, 2018 at 11:40
  • 1
    You are confusing a Date with its String representation. It's as if you're asking to use doubles that always print with 2 decimals -- numbers don't understand decimals or printing, only a formatter does. Commented Jun 6, 2018 at 11:46

1 Answer 1

5

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.

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

1 Comment

If I understood your concept, you mean to say that date will always remain the date but formatter will be its Beacon , beacon will come in different shapes but date will always remain the same as an entity. Just like human and clothes , human can wear different clothes but at the end that human is the same human

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.