Java convert time to long

Convert Date string with Time to long date

I have a string with date «10:00 AM 03/29/2011» , I need to convert this to a long using Java, I cant use Date because its deprecated and it was not giving me the time correctly.. so i looked online to see how to come about it but still no luck. First time using java.

Date isn’t deprecated. Several methods within it are, but that’s a different matter. You haven’t said what happens with the code you’ve provided.

I get a value like -58587811199953, and i am trying to come up with the correct way to get the long value., then when i enter it here epochconverter.com, it should give me the correct date, june 29 2013 8:00 AM

2 Answers 2

The problem is you’re parsing the data and then messing around with it for no obvious reason, ignoring the documented return value for Date.getYear() etc.

You probably just want something like this:

private static Date parseDate(String text) throws ParseException < SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a MM/dd/yyyy", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat.parse(text); >

If you really want a long , just use:

private static long parseDate(String text) throws ParseException < SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a MM/dd/yyyy", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat.parse(text).getTime(); >

Note that I’m punting the decision of what to do if the value can’t be parsed to the caller, which makes this code more reusable. (You could always write another method to call this one and swallow the exception, if you really want.)

As ever, I’d strongly recommend that you use Joda Time for date/time work in Java — it’s a much cleaner API than java.util.Date/Calendar/etc.

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API * .

Solution using java.time , the modern Date-Time API:

  1. Parse the Date-Time string into LocalDateTime .
  2. Convert the LocalDateTime to Instant .
  3. Convert Instant to the Epoch milliseconds.
import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Locale; public class Main < public static void main(String[] args) < String strDateTime = "10:00 AM 03/29/2011"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:m a M/d/u", Locale.ENGLISH); LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf); Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant(); long epochMillis = instant.toEpochMilli(); System.out.println(epochMillis); >> 

Output in my timezone, Europe/London:

Читайте также:  Изменить размер фрейма html

Some important notes about this code:

  1. ZoneId.systemDefault() gives you to the JVM’s ZoneId .
  2. If 10:00 AM 03/29/2011 belongs to some other timezone, replace ZoneId.systemDefault() with the applicable ZoneId e.g. ZoneId.of(«America/New_York») .
  3. If 10:00 AM 03/29/2011 is in UTC, you can do either of the following:
    • get the Instant directly as ldt.toInstant(ZoneOffset.UTC) or
    • replace ZoneId.systemDefault() with ZoneId.of(«Etc/UTC») in this code.
  4. The timezone of the Ideone server (the online IDE) is UTC whereas London was at an offset of +01:00 hours on 03/29/2011 and hence the difference in the output from my laptop and the one you see in the ONLINE DEMO. Arithmetic: 1301389200000 + 60 * 60 * 1000 = 1301392800000

Learn more about the modern Date-Time API from Trail: Date Time.

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Источник

Representation of current time into double/long in java [closed]

It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.

You can get current time via System.currentTimeMillis(). Then you can manipulate it by adding 1 for each millisecond you want to add (if you want to add a day, just use System.currentTimeMillis + (24*60*60*1000))

2 Answers 2

In Java the System.currentTimeMillis() is represented as a long already.

To convert to a double as fraction of the current day, you can find the start of the current day, subtract this from the current time and divide by the number of milli-seconds in a day.

Calendar calendar = Calendar.getInstance(); System.out.println(calendar.getTime()); System.out.println(calendar.getTimeInMillis());//your current time in long (milliseconds) calendar.set(Calendar.HOUR_OF_DAY, -24); System.out.println(calendar.getTime()); System.out.println(calendar.getTimeInMillis());//time, 24 hours earleir in long (milliseconds) 

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.25.43544

Читайте также:  Средняя зп senior java developer

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Convert current datetime to long in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

  • This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
  • This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.

I want to convert the current datetime to a long value in Java.

I know it has to be something with the DateTime

DateTime datetime = new DateTime(); 

But I couldn’t find a way to convert the dateTime to long.

4 Answers 4

The other answers are correct.

Four ways to count-from-epoch

To spell it out in detail, here are four ways to get the number of milliseconds since the Unix Epoch, the beginning of January 1, 1970 in UTC/GMT (no time zone offset). Presented in order of preference.

java.time

The java.time classes built into Java 8 and later is defined by JSR 310. These classes supplant the outmoded java.util.Date/Calendar classes. These classes are inspired by Joda-Time but are re-architected.

The java.time classes are capable of holding nanosecond resolution. In Java 8 specifically, capturing the current moment is limited to milliseconds, due to an old implementation of Clock . Java 9 brought a fresh implementation of Clock capable of capturing the current moment in finer resolution, limited by the capability of the host OS and host hardware. On Oracle JDK 9.0.4 on macOS Sierra, I get values in microseconds, for six digits of decimal fraction.

The Instant class includes a convenience method toEpochMilli provides milliseconds. Beware of data loss, as any microseconds or nanoseconds in the Instant are ignored when generating a count of milliseconds.

long millis = Instant.now().toEpochMilli(); 

System

The System class’ method currentTimeMillis works. But chances are that you are doing some other work with date-time values. If so, skip System and just use the date-time classes.

long millis = System.currentTimeMillis(); 

Joda-Time

Joda-Time is the popular third-party open-source library used in place of java.util.Date / Calendar . Its main class is DateTime , so perhaps this is what you had in mind given your question’s use of that term.

Читайте также:  Java collection save to file

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

long millis = org.joda.time.DateTime.now().getMillis(); 

java.util.Date

This class is best avoided, along with its siblings java.util.Calendar and java.text.SimpleDateFormat . The troublesome old date-time classes are now legacy, supplanted by java.time classes. But for your specific purpose, this class does work.

long millis = new java.util.Date().getTime(); 

By the way, I do not recommend tracking time as a count-from-epoch. Makes debugging difficult, and near impossible to spot invalid data as humans cannot interpret a long as a date-time. Also, ambiguous as different systems use different epoch reference dates, and use different granularities of whole seconds, milliseconds, microseconds, nanoseconds, and others.

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 .

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

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

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.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more.

    Источник

Оцените статью