-1

I have a set of helper methods that am currently using to format a date received from an API.

public static String ParseDate (String dateR) {
    SimpleDateFormat full_date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);

    try {
        full_date.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date = full_date.parse(dateR);

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        String day = GetDay(c.get(Calendar.DAY_OF_WEEK));
        int hr = c.get(Calendar.HOUR_OF_DAY);
        int min = c.get(Calendar.MINUTE);
        return day + ", " +  hr+ ":"  + min;
    } catch (Exception e) {
        System.err.println("Error" + e);
    }
    return dateR;
}

private static String GetDay(int d)
{
    switch (d)
    {
        case 1:
            return "Sunday";
        case 2:
            return "Monday";
        case 3:
            return "Tuesday";
        case 4:
            return "Wednesday";
        case 5:
            return "Thursday";
        case 6:
            return "Friday";
        case  7:
            return "Saturday";
        default:
            return "";

    }
}

I am calling these like this:

String str = "2013-09-11T12:50:00Z";
    System.out.println(ParseDate(str)); 

It works perfectly. However, I would like to improve its functionality. If the day of the week is not this current week, I would like to show the date rather than showing the day of the week. It would be wrong to show day of week when it is not a day from the current week.

Any help will be appreciated. Thank you

[UPDATE]:

For example: When date is : 2013-09-11T12:50:00Z I get this output: Wednesday, 18:20 This is wrong. A simple date like 24th May, 2013 will be better in this case.

This means that I need to be able to test whether the date falls in this week or exceeds then, should the format the date based on that. I hope am clear:)

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
  • please abbreviate with an `example` . Your question is not Cleared actually @Clinton – Vikrant Kashyap Apr 05 '16 at 06:14
  • I thought this was an example: String str = "2013-09-11T12:50:00Z"; System.out.println(ParseDate(str)); – Clinton Yeboah Apr 05 '16 at 06:17
  • I am not sure I understood. However, a nice improvement to your code would be replacing the numbers of the switch cases with the Calendar constants (e.g., replace 1 with Calendar.SUNDAY, 2 with Calendar.MONDAY, and so on). – maxvv Apr 05 '16 at 06:21
  • Ok thanks, and I have updated with an example :) – Clinton Yeboah Apr 05 '16 at 06:22
  • 1
    http://stackoverflow.com/questions/10313797/how-to-check-a-day-is-in-the-current-week-in-java check this link.Should help you fix – S.B Apr 05 '16 at 06:29

4 Answers4

1

Use

Calendar cNow = Calendar.getInstance(Locale.US);

Instead of

    return day + ", " +  hr+ ":"  + min;

use

SimpleDateFormat humanDateFormat = new SimpleDateFormat("E, HH:mm", Locale.US);
return (cNow.get(Calendar.WEEK_OF_YEAR) == c.getCalendar(Calendar.WEEK_OF_YEAR) ?
    humanDateFormat : full_date).format(c);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 2
    Be aware that `Calendar.WEEK_OF_YEAR` varies by `Locale`. That is, that class’ definition of a week varies, both the starting day (Sunday vs Monday etc.) and what marks week number 1. This vary-by-Locale may be good or bad depending on your needs. Best to always specify your desired/intended Locale rather then rely implicitly on the JVM’s current default locale. – Basil Bourque Apr 05 '16 at 06:45
1

java.time

You are using troublesome old date-time classes now outmoded by the java.time framework built into Java 8 and later. For Java 6 & 7 use the ThreeTen-Backport project. For Android, the adaptation of that project, ThreeTenABP. Avoid using the old classes; they really are that bad.

ISO 8601

Your input string complies with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to specify a formatting pattern.

Instant

An Instant is a moment on the timeline in UTC.

Instant instant = Instant.parse( "2013-09-11T12:50:00Z" );

Week Number

A week only makes sense in the context of a time zone, so we apply a time zone to get a ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Get the week number using the ISO 8601 standard definition of a week (week # 1 is first Thursday of Calendar year, running Monday-Sunday).

int weekNumberThen = zdt.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekNumberNow = ZonedDateTime.now( zoneId ).get( IsoFields.WEEK_OF_WEEK_BASED_YEAR );

Generate textual representation of date-time value

Finish up your business logic by testing for equality of the two week numbers. Note how we use the handy DayOfWeek enum to automatically localize to a display name for day of week. And note how we switch to LocalDate for format your date-only value output.

Locale locale = Locale.CANADA_FRENCH; // Or Locale.US, and so on.
String output = null;
if( weekNumberThen == weekNumberNow ) {
    DayOfWeek dayOfWeek = zdt.getDayOfWeek();
    output = dayOfWeek.getDisplayName( TextStyle.FULL , locale );
} else {
    LocalDate localDate = zdt.toLocalDate();
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale );
    output = localDate.format( formatter );
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

There is a problem with your code . I think you just copy paste this code from some other Sources and didn't understand the Code.

As per your code The output giving to you is fine.

 String day = GetDay(c.get(Calendar.DAY_OF_WEEK)); // this will return Day (Wednesday).

int hr = c.get(Calendar.HOUR_OF_DAY);  //return Hour of Date (18 in Your Case)

int min = c.get(Calendar.MINUTE);(Return Minutes ) (20 in Your Case)

return day + ", " +  hr+ ":"  + min; // return "Wednesday, 18:20"

So, Final Result what you get from Your method will be Wednesday, 18:20.

Just Change the above code will get your Answer.

int year = currentCalendar.get(Calendar.YEAR);
String month = currentCalendar.get(Calendar.MONTH);
int day = currentCalendar.get(Calendar.DAY_OF_MONTH);
 return day + "th " + month + " "  + year ; // return "24th February ,1991"
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
0

Perhaps if you ask for day of month would help?

int day = c.get(Calendar.DAY_OF_MONTH);

Then you can format as String like:

String currentDate = String.format("%d %s %d", day, monthName, year);

The result would be not "Wednesday", but 24.

The full date formatter could be:

Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
String monthName = null;
switch (month){
       case 0: monthName = "January"; break;
       case 1: monthName = "February"; break;
       case 2: monthName = "March"; break;
       case 3: monthName = "April"; break;
       case 4: monthName = "May"; break;
       case 5: monthName = "June"; break;
       case 6: monthName = "July"; break;
       case 7: monthName = "August"; break;
       case 8: monthName = "September"; break;
       case 9: monthName = "October"; break;
       case 10: monthName = "November"; break;
       case 11: monthName = "December"; break;
       default: break;
       }
int year = c.get(Calendar.YEAR);
String currentDate = String.format("%d %s %d", day, monthName, year);
Mihai Coman
  • 73
  • 1
  • 9