When should I use new?

5

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

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

In this example we did not use new :

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

When should I use new?

    
asked by anonymous 16.12.2015 / 12:52

3 answers

6

You must always use new to instantiate a class, that is, to 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 is why you do not need to use new . parse is a static method, which returns an object of type Date . In this case, it gets a String and its format and returns (returns) Date referenced.

    
16.12.2015 / 13:21
5

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

    
16.12.2015 / 13:34
2
  

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

String dataFormatada is receiving today's date in the format "dd / MM / yyyy";

  

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

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

new Date() will return today's date for you, and the format is for formatting any way you want.

    
16.12.2015 / 13:04