When should I wear the new one or not?

Asked

Viewed 426 times

5

What happens here? Why is an instance of Date in this example:

String dataFormatada = new Date().format("dd/MM/yyyy")

Already in this example was not used the new:

def data = Date.parse('dd/MM/yyyy', '31/12/1980')

When I should wear the new or not?

3 answers

6


You need to use the new always instantiate a class, that is, create a new instance of a given object. In this case, when you create a new instance of Date it already comes with the current date.

In the example

def data = Date.parse('dd/MM/yyyy', '31/12/1980')

You are not creating a new instance of Date and that’s why you don’t need to use the new. The parse is a static method, which returns an object of the type Date. In that case, he gets a String and the format of it and returns (returns) the Date referent.

5

@Aline, do not use new in def data = Date.parse('dd/MM/yyyy', '31/12/1980'), for Date#parse(String, String) is a static method not a constructor, and looking at the class Date, this method returns an instance of Date removal of an object Calendar by the method Calendar#getTime.

  • I think if I made a merge of that answer with that of durtto it would be quite complete :)

  • 1

    The jbueno has already edited his :D

2

String dataFormated = new Date(). format("dd/MM/yyyy")

A String dataFormatada is receiving today’s date in "dd/MM/yyyy format";

def data = Date.parse('dd/MM/yyyy', '31/12/1980')

data is receiving the value '31/12/1980'. As you already have the date, you do not need the new.

new Date() will return today’s date to you, and the format is to format the way you want it.

  • Ah, that’s all there is to it?

  • Yes. New Date will return today’s date to you. and the format is to format the way you want it.

  • got it. Thank you!

  • for nothing. it is a pleasure to help.

  • okay. Thanks. Does that apply to other examples as well? How to set a name of a person etc?

  • there’s another way for me to talk to you? durtto

  • @AlineGonz http://chat.stackexchange.com/rooms/11910/estouro-de-pilha

  • Aline, wait a moment. Don’t choose yet. Maybe we gave you a wrong context.

  • I think it got a little shallow, maybe if you dug a little deeper it would be better

  • the second does not use new because it is a static method of the class(Static). It was a response that I got about def data = Date.parse('dd/MM/yyyy', '31/12/1980') so we didn’t use the new. and there?

  • 1

    Static methods can be accessed directly from the class, not from an object, @Aline.

  • okay Gustavo, I get it.

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.