This question already has answers here:
Convert Json date to java date
(3 answers)
How can I convert Json Date to Java Date
(6 answers)
Closed 2 years ago.
so I have this problem converting Integer DateTime format to normal DateTime format in Java.
I have this this variable int DateTime, for example it is : "/Date(1484956800000)/" . And i am trying to convert it to normal date time and show it to the screen ...
I tried like this..
String dateAsText = new SimpleDateFormat("MM-dd HH:mm")
.format(new Date(Integer.parseInt(deals.getDate_time()) * 1000L));
// setting my textView with the string dateAsText
holder.Time.setText(dateAsText);
I suggest you stop using the outdated and error-prone java.util date-time API and SimpleDateFormat. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Obtain an instance of Instant using milliseconds from the epoch of
// 1970-01-01T00:00:00Z
Instant instant = Instant.ofEpochMilli(1484956800000L);
System.out.println(instant);
// Specify the time-zone
ZoneId myTimeZone = ZoneId.of("Europe/London");
// Obtain ZonedDateTime out of Instant
ZonedDateTime zdt = instant.atZone(myTimeZone);
// Obtain LocalDateTime out of ZonedDateTime
// Note that LocalDateTime throws away the important information of time-zone
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// Custom format
String dateAsText = ldt.format(DateTimeFormatter.ofPattern("MM-dd HH:mm"));
System.out.println(dateAsText);
}
}
Output:
2017-01-21T00:00:00Z
2017-01-21T00:00
01-21 00:00
If you still want to use the poorly designed legacy java.util.Date, you can do it as follows:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date(1484956800000L);
System.out.println(date);
// Custom format
String dateAsText = new SimpleDateFormat("MM-dd HH:mm").format(date);
System.out.println(dateAsText);
}
}
Output:
Sat Jan 21 00:00:00 GMT 2017
01-21 00:00
Related
I having a hard time trying to format a string time into MM:DD::YY and only time. From an IP i getting the time in the following format
2021-09-10T00:37:42Z
and I'm want to display the date and time in:
09/08/2021
Time
09:50PM
Parse the given string into OffsetDateTime and then get LocalDate and LocalTime parts out of it.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021-09-10T00:37:42Z";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
LocalTime time = odt.toLocalTime();
LocalDate date = odt.toLocalDate();
System.out.println(time);
System.out.println(date);
// #########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String formattedDateString = date.format(dtfDate);
System.out.println(formattedDateString);
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime);
System.out.println(formattedTimeString);
}
}
Output:
00:37:42
2021-09-10
09/10/2021
12:37 AM
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
Update based on an important comment by Ole V.V.:
The OP — or their user — may want the date and time in their own time
zone.
In order to get the date and time parts in a specific timezone e.g. America/Los_Angeles, you should parse the given date-time string into ZonedDateTime and convert the same to the ZonedDateTime of the specific timezone using ZonedDateTime#withZoneSameInstant. Rest of the things will remain same as the original answer.
Demo:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021-09-10T00:37:42Z";
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime);
ZonedDateTime zdtLosAngeles = zdt.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
LocalTime time = zdtLosAngeles.toLocalTime();
LocalDate date = zdtLosAngeles.toLocalDate();
System.out.println(time);
System.out.println(date);
// #########Custom formats #########
DateTimeFormatter dtfDate = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String formattedDateString = date.format(dtfDate);
System.out.println(formattedDateString);
DateTimeFormatter dtfTime = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String formattedTimeString = time.format(dtfTime);
System.out.println(formattedTimeString);
}
}
Output:
17:37:42
2021-09-09
09/09/2021
05:37 PM
ONLINE DEMO
* 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.
I would like to generate a DateTime variable from two different variables (get the date from myLongDateAndTime and time from myStringTime, how can I do that?
String myStringTime="12:30:10"; // Come from DB
long myLongDateAndTime= 1628197200000 // Come from another DB stores date and times in timestamp format of Thu Aug 05 2021 17:00:00 GMT-0400
DateTime myDateTime=??? // should get Thu Aug 05 2021 12:30:10
java.time
Quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
Instant instant = Instant.ofEpochMilli(myLongDateAndTime);
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-04:00"));
System.out.println(odt);
odt = odt.with(time);
System.out.println(odt);
}
}
Output:
12:30:10
2021-08-05T21:00:00Z
2021-08-05T17:00-04:00
2021-08-05T12:30:10-04:00
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness
Just for the sake of completeness, given below is the solution using the Joda Date-Time API:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
String myStringTime = "12:30:10";
long myLongDateAndTime = 1628197200000L;
LocalTime time = LocalTime.parse(myStringTime);
System.out.println(time);
DateTime dateTime = new DateTime(Long.valueOf(myLongDateAndTime), DateTimeZone.forOffsetHours(-4));
System.out.println(dateTime);
dateTime = dateTime.withTime(time);
System.out.println(dateTime);
}
}
Output:
12:30:10.000
2021-08-05T17:00:00.000-04:00
2021-08-05T12:30:10.000-04:00
* 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.
You are combining two dates, so what you need to do is:
create a joda DateTime from the long
format that DateTime to a string with only the date part
combine with date string and time string in a single string
parse the new string
and here is how you can do that:
public DateTime combineDates(long myLongDateAndTime, String myStringTime) {
// 1 - create DateTime from the long
DateTime dateFromLong = new DateTime(myLongDateAndTime);
// 2 - Format dateFromLong as date string
DateTimeFormatter dtfDate = DateTimeFormat.forPattern("dd/MM/yyyy");
String dateString = dtfDate.print(dateFromLong);
// 3 - Concatenate date part and time part in a new string
String completeDate = dateString + " " + myStringTime;
// 4 - Parse the new string in to a DateTime
DateTimeFormatter dtfDateTime =
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
return dtfDateTime.parseDateTime(completeDate);
}
This is only a possible solution. There are many other ways to do the same, for example without using a string concatenation, but only dates operations, but this way is quite clear and readable, so I don't investigate additional possible solutions.
One possible solution:
public class TestSample {
public static void main(String[] args) {
String myStringTime="12:30:10";
Long myLongDateAndTime= 1628197200000L;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
LocalTime time = LocalTime.parse(myStringTime, formatter);
LocalDate date = Instant.ofEpochMilli(myLongDateAndTime).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime dtTime = LocalDateTime.parse(date.toString()+" "+time.toString(), formatter1);
System.out.println(dtTime.toString());
}
}
This question already has answers here:
Is java.time failing to parse fraction-of-second?
(3 answers)
Closed 1 year ago.
Hello I try parse String 20110330174824917 to OffsetDateTime using DateTimeFormatter so
public static void main(String[] args) {
// System.out.println(OffsetDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
System.out.println(LocalDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
}
but I get
Exception in thread "main" java.time.format.DateTimeParseException: Text '20110330174824917' could not be parsed, unparsed text found at index 8
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
Hey guys it looks like this problem is related with java 8
https://bugs.openjdk.java.net/browse/JDK-8031085
Thank you all for help
DateTimeFormatter#withZone
Your date-time string does not have timezone information and therefore, in order to parse it into OffsetDateTime, you need to pass the timezone information explicitly. You can use DateTimeFormatter#withZone to parse the date-time string into ZonedDateTime which you can convert to OffsetDateTime using ZonedDateTime#toOffsetDateTime.
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "20110330174824917";
// Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
OffsetDateTime odt = ZonedDateTime.parse(strDateTime, dtf)
.toOffsetDateTime();
System.out.println(odt);
}
}
Output:
2011-03-30T17:48:24.917+01:00
You can define the used Zone for the Formatter and concatenate the input string with the correct Zone Offset
// note the added Z at the end of the pattern for the offset
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSZ").withZone(ZoneId.of("UTC"));
OffsetDateTime dateTime = OffsetDateTime.parse("20110330174824917" + "+0000", formatter);
This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Convert String date into java.util.Date in the dd/MM/yyyy format [duplicate]
(1 answer)
return date type with format in java [duplicate]
(1 answer)
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 3 years ago.
I have a requirement to convert String to Date (in dd-MM-yyyy format). But dateformat.parse gives the format with seconds. I need to convert the String date to Date in the same format as mentioned above.
The class Date will always contain both date a nd time information, since it represents an instant in time.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d;
try {
d = fmt.parse("04-12-2019");
System.out.println(d); // Wed Dec 04 00:00:00 CET 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}
As you can see, hours, minutes, seconds and millis get all set to 0.
If you later want to output the date in string format, you need to use the DateFormat#format(Date) method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d = new Date();
System.out.println(d); // Wed Dec 04 11:24:35 CET 2019
System.out.println(fmt.format(d)); // 04-12-2019
}
}
If you'd rather store only date information, you could use the java.time package and make use of LocalDate.
LocalDate stores only date information, since it does not represent an instant, rather a triple of year, month and date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ParsingLocalDate {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("04-12-2019", fmt);
System.out.println(d); // 2019-12-04
}
}
If you do not need to use time of day or time zone, you can parse it by LocalDate.
String str = "01-01-2000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.parse(str, formatter);
Note that for day and time people most of the time would want a ZonedDateTime rather than a LocalDateTime. The name is counter-intuitive; the Local in both LocalDate and LocalDateTime means any locality in general rather than a specific time zone.
In most programming languages, date/time types are simply containers for the amount of time which has passed from a given point in time. They don’t have a format.
In the case of Java (AFAIR), time is measured in milliseconds since the Unix Epoch.
Since it's 2019, there is no excuse not to making use of the java.time APIs (or the ThreeTen backport) and you should avoid using the, now effectively deprecated, older APIs
Parse String to LocalDate
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.parse("08-03-1972", inputFormatter);
Format LocalDate to desired format
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd EEE MMM yyyy");
String value = localDate.format(outputFormatter);
System.out.println(value);
which outputs
08 Wed. Mar. 1972
I have a formatted date from sqllite database, to use this in a graph view I need to format it in a long number.
The format is:
2012-07-11 10:55:21
how can I convert it to milliseconds?
You can convert the string into a Date object using this code:-
Date d = DateFormat.parse(String s)
And then convert it into milliseconds by using the inbuilt method
long millisec = d.getTime();
Use date.getTime()
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss");
formatter.setLenient(false);
String oldTime = "2012-07-11 10:55:21";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();
try this:
import java.util.*;
public class ConvertDateIntoMilliSecondsExample{
public static void main(String args[]){
//create a Date object
Date date = new Date();
System.out.println("Date is : " + date);
//use getTime() method to retrieve milliseconds
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : "
+ date.getTime());
}
}
java.time
Solution using java.time, the modern date-time API*:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toMillis("2012-07-11 10:55:21"));
}
public static long toMillis(String strDateTime) {
// Replace the parameter, ZoneId.systemDefault() which returns JVM's default
// timezone, as applicable e.g. to ZoneId.of("America/New_York")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
Instant instant = zdt.toInstant();
return instant.toEpochMilli();
}
}
Output:
1342000521000
Learn more about the 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.