DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

HackerRank #8 | Date and Time | 🇧🇷

Date And Time

Esse exercício propõe usar a classe Calendar para construir uma saída com apenas o dia da semana a partir de um input de mês, dias e ano (nessa ordem).

Exemplo:


month = 8
day = 05
year = 2015

Enter fullscreen mode Exit fullscreen mode

SaĂ­da: WEDNESDAY // (em letras maiĂşsculas)

O problema começa com o seguinte código:


class Result {

    public static String findDay(int month, int day, int year) {
    }

Enter fullscreen mode Exit fullscreen mode
  • Primeiro, criei uma variável calendário que pega o mĂ©todo .getInstance();

É preciso usar o método estático .getInstance() porque a classe Calendar é abstrata e não pode ser instanciada.

  • Depois, usando os setters, definimos mĂŞs, dia e ano.

Os meses do ano estão num array de 0 a 11, por isso não dá pra colocar simplesmente month , sendo necessário botar -1. Dessa forma, se o input for 2 (número do mês de fevereiro normalmente), lerá na verdade -1 + 2, dando 1 (fevereiro, no array de month).

  • Por fim, retornamos o calendário junto do mĂ©todo .getDisplayName(). Esse mĂ©todo exige trĂŞs parâmetros: (field, style, locale). O field sĂŁo os campos necessários (DAY_OF_WEEK, MONTH, etc); o style Ă© o parâmetro (.LONG, .SHORT, etc); e locale Ă© o local. Como a saĂ­da precisa ser em inglĂŞs, precisamos colocar .US ou .CANADA, nĂŁo funciona .GERMANY ou .FRANCE.

  • E o .toUpperCase() porque o problema pedia para estar em maiĂşsculo.

O resultado Ă© o seguinte:


class Result {

    public static String findDay(int month, int day, int year) {
        Calendar calendario = Calendar.getInstance();
        calendario.set(Calendar.MONTH, month-1);
        calendario.set(Calendar.DAY_OF_MONTH, day);
        calendario.set(Calendar.YEAR, year);
        return calendario.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
    }

}

Enter fullscreen mode Exit fullscreen mode

============

Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa:

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

đź‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay