【问题标题】:Java - Know the day of the week of the given StringJava - 知道给定字符串的星期几
【发布时间】:2015-03-30 18:58:40
【问题描述】:

在 android 中,我有一个 "2015-03-30T12:30:00" 格式的字符串,我想知道它是星期几。

在同一天用设备测试,有那个功能dayOfweek = 5dayOfWeek2 = 2为什么?

如果我尝试使用 year , month , day 创建一个新的 Date 它的说法已被弃用...

public int devolverDia(String hora)
{
    hora = hora.substring(0, 10);
    String weekdays[] = new DateFormatSymbols(Locale.ENGLISH).getWeekdays();
    Calendar c = Calendar.getInstance();

    int year = Integer.parseInt(hora.substring(0, 4));
    int month = Integer.parseInt(hora.substring(5, 7));
    int day = Integer.parseInt(hora.substring(8, 10));

    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DAY_OF_MONTH, day);

    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);


    c.setTime(new Date());
    int dayOfWeek2 = c.get(Calendar.DAY_OF_WEEK);


    return dayOfWeek;
}

【问题讨论】:

    标签: java android calendar dayofweek


    【解决方案1】:

    你没有得到你期望的日期的原因是这条线

    c.set(Calendar.MONTH, month);
    

    需要从 0(1 月)到 11(12 月)的月份数。如果您将其替换为

    c.set(Calendar.MONTH, month - 1);
    

    此代码将起作用。

    但是,更好的解决方案是使用SimpleDateFormat classparse 方法将您的String 转换为Date

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    c.setTime(format.parse(hora));
    

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 2018-03-04
      • 1970-01-01
      • 2021-06-29
      • 2019-12-09
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多