【问题标题】:I want this method to convert and get value in miliseconds [duplicate]我希望这种方法在毫秒内转换并获得价值[重复]
【发布时间】:2019-04-13 11:45:16
【问题描述】:

我该怎么做?我尝试了很多,但它无法正常工作。

public static String getDateTime() {
        String dateStr = "";
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateStr = dateFormat.format(date);
        return dateStr;
    }

请有人纠正另一种从上述日期格式返回毫秒的方法。当然!在我的数据库中,我存储了这个值:2019-04-17 17:11:02 -> 我希望这个值使用一种方法以毫秒为单位进行转换。这样我就可以调用新方法并传递该变量值。

【问题讨论】:

  • 您只想转换时间或时间+日期?
  • 当您从数据库中获取并希望将其转换回日期对象和毫秒时,您是否有上述格式的字符串日期?这是你想要的吗?
  • 当我从数据库中取回字符串值时,我希望该值以毫秒为单位转换并在 long 变量中运行
  • @AsadChoudhary chk
  • @Mr.AF 当我从 DB 取回 String 值时,我希望该值以毫秒为单位转换并在 long 变量中存储 -

标签: java android datetime


【解决方案1】:
 public static long milisecondsFromDate(String dateStr) {

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date date = formatter.parse(dateStr);
        return date.getTime();
    } catch (Exception e) {
        Log.e("Tag", "Wrong date Format");
    }
    return -1;
}

【讨论】:

  • 我想以毫秒为单位存储价值
  • 上述方法已经返回毫秒。您是否遇到任何问题,请告诉我。
【解决方案2】:

我强烈建议您使用 Java8 日期/时间 API,例如:

public static void main(String[] args) {
    System.out.println(getDateTime());
}

public static String getDateTime() {
    String dateStr = "2019-04-17 17:11:02";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
    LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);

    return String.valueOf(localDateTime.toInstant(ZoneOffset.UTC).getEpochSecond());
}

【讨论】:

    【解决方案3】:

    试试这个:-

           long timeInMilliseconds = 0;
            String givenDateString = "2019-04-17 17:11:02";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date mDate = sdf.parse(givenDateString);
                timeInMilliseconds = mDate.getTime();
            } catch (ParseException e) {
                        e.printStackTrace();
            }
    
    String timeInMilliseconds = String.valueOf(timeInMilliseconds);
    

    【讨论】:

    • 如有任何疑问请留言
    • 我想以毫秒为单位存储价值
    • 毫秒总是存储在 long 类型中。
    • 如果这个答案对你有用,那么感谢这个答案.....?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多