Can I get value of Curren time from miliseconds value [duplicate] - java

This question already has answers here:
How to display time amount to user?
(1 answer)
Java 8 epoch-millis time stamp to formatted date, how?
(3 answers)
Closed 2 years ago.
I have a value in miliseconds 1601626934449
Which generated via https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()
but can I somehow be able to get time in human readable format, or in brief I need to be able to know what the value in miliseconds 1601626934449 is ?

Use java.time on Java 8 or higher. Using that, it's easy to reach your goal.
You basically create an Instant from the epoch milliseconds (which represent a moment in time), make it a ZonedDateTime by applying a ZoneId (my system's default in the following example) and then either format the output String by a built-in DateTimeFormatter or by creating a custom one with a desired pattern to make it as human-readable as required.
Here's an example:
public static void main(String[] args) {
// your example millis
long currentMillis = 1601626934449L;
// create an instant from those millis
Instant instant = Instant.ofEpochMilli(currentMillis);
// use that instant and a time zone in order to get a suitable datetime object
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
// then print the (implicitly called) toString() method of it
System.out.println(currentMillis + " is " + zdt);
// or create a different human-readable formatting by means of a custom formatter
System.out.println(
zdt.format(
DateTimeFormatter.ofPattern(
"EEEE, dd. 'of' MMMM uuuu 'at' HH:mm:ss 'o''clock in' VV 'with an offset of' xxx 'hours'",
Locale.ENGLISH
)
)
);
}
which outputs (on my system)
1601626934449 is 2020-10-02T10:22:14.449+02:00[Europe/Berlin]
Friday, 02. of October 2020 at 10:22:14 o'clock in Europe/Berlin with an offset of +02:00 hours

You can convert millis into LocalDateTime to store time
long millis = System.currentTimeMillis();
LocalDateTime datetime = Instant.ofEpochMilli(millis)
.atZone(ZoneId.systemDefault()).toLocalDateTime();
Then you can print your data using toString() or your desire format using DateTimeFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
System.out.println(datetime.format(formatter));
Output: 2020-10-02 18:39:54.609

You can create a Date object and use it to get all the information you need:
https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#Date(long)

Related

Selenium java Date Time validation issue

I have a requirement where I have to extract the date and time displayed on the screen, which is in following format: 2021 Jul 12 # 06:30
And I have to compare this with a specific timezone to check whether they are equal or not.
Can anyone please help me with the way to handle this logic in Selenium Java (any version)?
Assuming you are retrieving the date time as a string, you can use a combination of ZonedDateTime and LocalDateTime as follows:
First we get your system zone and zoned datetime:
ZoneId timeZone = ZoneId.systemDefault();
LocalDateTime nowLocalDateTime = LocalDateTime.now();
ZonedDateTime nowZonedDateTime = ZonedDateTime.of(localDateTime, timeZone);
Then we define the pattern using formatter, and use it to format the example string to a ZonedDateTime object:
DateTimeFormatter exampleFormatter = DateTimeFormatter.ofPattern("yyyy MMM dd # HH:mm");
String example = "2021 Jul 12 # 06:30";
ZonedDateTime exampleZonedDateTime = LocalDateTime.parse(example, formatter).atZone(timeZone);
Here, I used the system timezone but you can change this to the zone you like assuming you know the time zone of the example.
This way we can compare exampleZonedDateTime with nowZoned DateTime where:
nowZonedDateTime holds the systems current defined timezone
exampleZonedDateTime holds the Zoned date time you want to compare with.
Also you can convert both to LocalDateTime objects using .toLocalDateTime() method in the ZonedDateTime class.

how to convert date in yyyy-MM-dd format of date type? [duplicate]

This question already has answers here:
Change date format in a Java string
(22 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
How to convert date in to yyyy-MM-dd Format?
(6 answers)
display Java.util.Date in a specific format
(11 answers)
Closed 3 years ago.
I know that this question that I am asking has answer all over the net but I want the yyyy-MM-dd format in Date type as SimpleDateFormat.format("yyyy-MM-dd") returns the string value and also I have tried SimpleDateFormat.parse("yyyy-MM-dd") but it does not provide the value in required format. Could anyone help how to get "yyyy-MM-dd" format in Date type variable. Example what I am trying to do is shown below-
Date date = new Date(); // this will give the outpur something like this Thu 28 Nov....
But I want the output in this format 2019-11-28 where date variable should not change its type.
tl;dr
Capture the current date, using java.time.LocalDate.
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.now( // Capture the current date. Time zone required, as the date is not the same around the globe.
ZoneId.of( "Pacific/Auckland" )
) // Returns a `LocalDate` object.
.toString() // Generates a `String` object whose text is in standard ISO 8601 format: YYYY-MM-DD
2020-01-23
Perhaps you are being handed a java.util.Date object by old code not yet updated to java.time classes. Convert from a given java.util.Date object (legacy) to Instant & ZonedDateTime (modern).
myJavaUtilDate // `java.util.Date` is one of the terrible date-time classes, now legacy.
.toInstant() // Convert to the modern `java.time.Instant` class that replaces `Date`.
.atZone( // Adjust from UTC to the time zone through which you want to perceive the date.
ZoneId.of( "Asia/Tokyo" ) // Specify a proper time zone in `Continent/Region` format, never 2-4 letter pseudo-zone such as PDT, CST, IST, and such.
) // Returns a `ZonedDateTime` object.
.format( // Generate text representing the value within our `ZonedDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE // Specify a formatter. Here, the standard ISO 8601 formatter for date-only value: YYYY-MM-DD.
) // Returns a `String`.
2020-01-23
java.time
You are using terrible date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.
LocalDate
If you just want the current date, use LocalDate.now.
LocaleDate.now( ZoneId.of( "Europe/Berlin" ) ).toString() // Yields something like '2020-01-23'.
Instant
Convert java.util.Date to its replacement, java.time.Instant. Both represent a moment in UTC, though the modern class has a fiber resolution of nanoseconds versus milliseconds.
To convert, use new to/from methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
ZonedDateTime
For any given moment, the date varies around the globe by time zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.
So determining a date requires a time zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Text
Could anyone help how to get "yyyy-MM-dd" format in Date type variable.
Text has a “format”, but date-time objects do not. Date-time objects can be instantiated by parsing text. Date-time objects can generate text to represent t the value held internally. But the date-time object and the String object are separate and distinct.
Generate text for the date only, without the time of day and without the time zone appearing.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE ) ;
Convert it to java.sql.Date :
Date obj = new Date();
java.sql.Date sqlDate = new java.sql.Date(obj.getTime());
System.out.println(sqlDate);
Try this one:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String strDate= formatter.format(date);
System.out.println(strDate);
or check this site: https://www.javatpoint.com/java-simpledateformat
I don't think that you can change the format of a Date object itself, therefore you should use DateFormatters, like mentioned above the SimpleDateFormat.
Also, you maybe should consider using LocalDate/LocalDateTime or Instant instead of Date.

UTC time in java? [duplicate]

This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(33 answers)
Closed 4 years ago.
How can I get UTC value in Java of any given time and date with the respective time-zone?
Say for example my current time zone is Asia/Kolkata, now how can I get UTC value of say 1.00 am on 21/07/2018?
For getting currect time in UTC.
Instant.now() // Current time in UTC.
For getting current time in any desired TimeZone.
ZonedDateTime.now( ZoneId.systemDefault() ) // Current time in your ZoneId.
Kolkata Example :
ZoneId zoneKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
To adjust back to UTC, extract an Instant from the ZonedDateTime.
Instant instant = zoneDTKolkata.toInstant() ;
You can adjust from UTC to a time zone.
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
Use the Java 8 time API instead of the older API (ie Date & SimpleDateFormat solution proposed by rajadilipkolli)
// System time (ie, your operating system time zone)
LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, minute, second);
// Time in Asia/Kolkata
ZonedDateTime kolkata = ldt.atZone(ZoneId.of("Asia/Kolkata"));
// Time in UTC
OffsetDateTime utc = ldt.atOffset(ZoneOffset.UTC);
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h.mm a 'on' dd/MM/uuuu")
.toFormatter(Locale.ENGLISH);
ZoneId zone = ZoneId.of("Asia/Kolkata");
String localDateTimeString = "1.00 am on 21/07/2018";
Instant i = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant();
System.out.println("UTC value is: " + i);
This prints:
UTC value is: 2018-07-20T19:30:00Z
I wasn’t sure whether you needed to parse the exact string you gave, 1.00 am on 21/07/2018, into a date-time object, but in case I have shown how. The challenge is that am is in lowercase. In order to specify case insensitive parsing I needed to go through a DateTimeFormatterBuilder.
As you can see, the code converts to an Instant, which is the modern way to represent a point in time in Java. Instant.toString always prints the time in UTC. The Z at the end means UTC. If you want a date-time that is more explicitly in UTC you may use
OffsetDateTime odt = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant()
.atOffset(ZoneOffset.UTC);
System.out.println("UTC value is: " + odt);
The output is similar, only OffsetDateTime leaves out the seconds if they are 0 (zero):
UTC value is: 2018-07-20T19:30Z
Link: Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API.

Java - how to parse yyyy-mm-ddThh:mm:ssZ to a specific time zone and format? [duplicate]

This question already has answers here:
Parsing ISO-8601 DateTime with offset with colon in Java
(4 answers)
Closed 5 years ago.
how to parse yyyy-mm-ddThh:mm:ssZ into my specific timezone and only display the time?
For example:
from 2017-11-22T22:00:00Z
to 2017-11-22 23:00
Because my timezone is one hour ahead of the timezone that the first string was from, I hope you understand!
If using Java 8, you can parse it as an Instant and then convert it to a ZonedDateTime in the time zone you need. You can then get the local time from the ZonedDateTime.
Instant instant = Instant.parse("2017-11-22T22:00:00Z");
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(zdt.toLocalTime());
You can also specify a specific Zone ID other than the system default. To see the available Zone IDs to choose from, use ZoneId.getAvailableZoneIds())
Using ZonedDateTime will handle daylight savings. If you simply need a static hour offset, you can convert it to an OffsetDateTime instead of the ZonedDateTime.
First, parse your string as an Instant, then convert that to a ZoneDateTime in the desired zone; from that, you can obtain the LocalTime
LocalTime time = Instant.parse(str).atZone(ZoneId.systemDefault()).toLocalTime();
Java DateFormater
String date = "2011-01-18 00:00:00";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date parsedDate = dateFormat.parse(date);

How to get Date in UTC+0 in Java? [duplicate]

This question already has answers here:
Why is string to date and back to string resulting in two different strings?
(2 answers)
Closed 1 year ago.
I am using the following code to get the date in ISO-8601 format. For UTC the value returned does not contain offset.
OffsetDateTime dateTime = OffsetDateTime.ofInstant(
Instant.ofEpochMilli(epochInMilliSec), zoneId);
return dateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
For other time formats the response returned looks like:
2016-10-30T17:00:00-07:00
In case of UTC the value returned is:
2016-10-30T17:00:00Z
I want it to be:
2016-10-30T17:00:00+00:00
Note: Do not use UTC-0 as -00:00 is not ISO8601 compliant.
The built-in formatter uses Z when the offset is zero. The Z is short for Zulu and means UTC.
You'll have to use a custom formatter, using a java.time.format.DateTimeFormatterBuilder to set a custom text for when the offset is zero:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date and time, use built-in
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// append offset, set "-00:00" when offset is zero
.appendOffset("+HH:MM", "-00:00")
// create formatter
.toFormatter();
System.out.println(dateTime.format(fmt));
This will print:
2016-10-30T17:00:00-00:00
Just reminding that -00:00 is not ISO8601 compliant. The standard allows only Z and +00:00 (and the variations +0000 and +00) when the offset is zero.
If you want +00:00, just change the code above to:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date and time, use built-in
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// append offset
.appendPattern("xxx")
// create formatter
.toFormatter();
This formatter will produce the output:
2016-10-30T17:00:00+00:00
If you can accept +00:00 instead of -00:00, you can also use a simpler DateTimeFormatter:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxxx");
OffsetDateTime odt = OffsetDateTime.parse("2016-10-30T17:00:00Z");
System.out.println(fmt.format(odt));
I used x whereas the standard toString() method of OffsetDateTime uses X. The main difference between x and X is that one return +00:00 vs. Z for the other.

Categories