Date to local time kotlin - java

I have a date object with
"Sun Apr 26 11:44:00 GMT+03:00 2020"
I tried to format it but it will always ignore the timezone "+3:00" and show the hour without changing it
what I have tried :
val sdf = SimpleDateFormat("dd MM yyyy HH:mm:ss", Locale.US)
return sdf.format(this)

I don't exactly understand your question but I guess you meant you need DateTime related to a particular zone. In kotlin we've ZonedDateTime class
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
val londonZone = ZoneId.of("Europe/London")
val londonCurrentDateTime = ZonedDateTime.now(londonZone)
println(londonCurrentDateTime) // Output: 2018-01-25T07:41:02.296Z[Europe/London]
val londonDateAndTime = londonCurrentDateTime.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM))
println(londonDateAndTime) // Output: Thursday, January 25, 2018 7:40:34 AM
You also might need to take a look at LocalDateTime class.

If you just want to parse a datetime String with the given pattern and then convert the result to a different offset, you can go like this:
fun main() {
// provide the source String
val datetime = "Sun Apr 26 11:44:00 GMT+03:00 2020"
// provide a pattern for parsing
val parsePattern = "E MMM dd HH:mm:ss O yyyy";
// parse the String to an OffsetDateTime
val parsedOffsetDateTime = java.time.OffsetDateTime.parse(
datetime,
java.time.format.DateTimeFormatter.ofPattern(parsePattern))
// print the result using the default format
println(parsedOffsetDateTime)
// then get the same moment in time at a different offset
val adjustedOffsetDateTime = parsedOffsetDateTime.withOffsetSameInstant(
java.time.ZoneOffset.of("+02:00"))
// and print that, too, in order to see the difference
println(adjustedOffsetDateTime)
}
which produces the output
2020-04-26T11:44+03:00
2020-04-26T10:44+02:00

The format string depends on which SimpleDateFormat you use:
If using java.text.SimpleDateFormat with API Level 24+, the format string needs to be:
"EEE MMM d HH:mm:ss 'GMT'XXX yyyy"
If using android.icu.text.SimpleDateFormat, the format string needs to be:
"EEE MMM d HH:mm:ss OOOO yyyy".
Demo (in plain Java)
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Jerusalem"));
Date date = new Date(1587890640000L); // date object with "Sun Apr 26 11:44:00 GMT+03:00 2020"
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss 'GMT'XXX yyyy", Locale.US);
String dateString = sdf.format(date);
System.out.println("Formatted : " + dateString);
Date parsed = sdf.parse(dateString);
System.out.println("Parsed back: " + parsed);
System.out.println("Millis since Epoch: " + parsed.getTime());
Output
Formatted : Sun Apr 26 11:44:00 GMT+03:00 2020
Parsed back: Sun Apr 26 11:44:00 IDT 2020
Millis since Epoch: 1587890640000

Related

How do I convert this time format into epoch in java? "Tue Dec 28 16:55:00 GMT+05:30 2021" to Epoch

I am using 'Single Date and Time Picker' Library in my Android Project but it only returns date and time in the below mentioned format.
"Tue Dec 28 16:55:00 GMT+05:30 2021"
I want to convert this into epoch time format.
Library:
https://github.com/florent37/SingleDateAndTimePicker
Alternative solution with java.time.OffsetDateTime
Here's an alternative solution that makes use of java.time keeping all the information of the input String:
public static void main(String[] args) throws IOException {
// input
String dpDate = "Tue Dec 28 16:55:00 GMT+05:30 2021";
// define a formatter with the pattern and locale of the input
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
// parse the input to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dpDate, dtf);
// receive the moment in time represented by the OffsetDateTime
Instant instant = odt.toInstant();
// extract its epoch millis
long epochMillis = instant.toEpochMilli();
// and the epoch seconds
long epochSeconds = instant.getEpochSecond();
// and print all the values
System.out.println(String.format("%s ---> %d (ms), %d (s)",
odt, epochMillis, epochSeconds));
}
Output:
2021-12-28T16:55+05:30 ---> 1640690700000 (ms), 1640690700 (s)
A LocalDateTime should not be used here, because you may lose the information about the offset and a ZonedDateTime can neither be used due to the input lacking information about a zone like "Asia/Kolkata" or "America/Chicago", it just provides an offset from UTC.
If you simply want to get the epoch millis, you can write a short method:
// define a constant formatter in the desired class
private static final DateTimeFormatter DTF_INPUT =
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
…
/**
* parses the input, converts to an instant and returns the millis
*/
public static long getEpochMillisFrom(String input) {
return OffsetDateTime.parse(input, DTF_INPUT)
.toInstant()
.toEpochMilli();
}
The format for your date is EEE MMM dd HH:mm:ss zzzz yyyy
String date = "Tue Dec 28 16:55:00 GMT+05:30 2021";
try {
val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy")
val mDate = sdf.parse(date)
val epochTime = TimeUnit.MILLISECONDS.toSeconds(mDate.time)
} catch (e: ParseException) {
e.printStackTrace()
}
Variable epochTime will have the seconds stored in it.
To convert it back to a format you can do -
val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy")
sdf.format(epochTime)
Latest Java 8 Requires Min Api Level 26
String date = "Tue Dec 28 16:55:00 GMT+05:30 2021";
DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
LocalDateTime parsedDate = LocalDateTime.parse(date, format);
val milliSeconds = parsedDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
By Following Ansari's Answer, I did this to convert it into Epoch
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.ENGLISH);
Date d1 = null;
try{
d1 = sdf3.parse("Tue Dec 28 16:55:00 GMT+05:30 2021");
epochTime = TimeUnit.MILLISECONDS.toSeconds(d1.getTime());
Log.e("epoch time", "onDateSelected: "+epochTime );
}
catch (Exception e){ e.printStackTrace(); }

Trouble formatting date in Java [duplicate]

This question already has answers here:
DateTimeParse Exception
(2 answers)
Closed 2 years ago.
I've tried several methods with Java Joda Time, Date Time with locale and commons-lang and can't get this date formatted.
Input
Mon Dec 28 15:18:16 UTC 2020
Output
Desired output format yyyy-MM-dd HH:mm:ss.SSS
When I use a format pattern like EEE MMM dd HH:mm:ss Z YYYY the date is off my a couple days and the timezone seems completely wrong.
Formatter:
private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
.withLocale(Locale.US)
.withZone(ZoneId.systemDefault());
DateUtils.parseDate (Optional
.ofNullable(record)
.map(CustomerModel::getCustomerAudit)
.map(customerAudit::getCreated)
.map(auditItem::getDate).get ().toString (), "EEE MMM dd HH:mm:ss YYYY")
When debugging parsing issues, if possible, reverse the operation and generate the text you're supposed to be parsing, to verify the parsing rules, i.e. the date format string. This applies to date parsing, JAXB parsing, and any other (de)serializing operation that is bi-directional. It makes finding conversion rule issues a lot easier.
So, let us check the format string in the question, with the shown date value:
ZonedDateTime dateTime = ZonedDateTime.of(2020, 12, 28, 15, 18, 16, 0, ZoneOffset.UTC);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss Z YYYY", Locale.US);
System.out.println(dateTime.format(fmt));
Output
Mon Dec 28 15:18:16 +0000 2021
Oops! That doesn't fit the expected output, aka the input we desire to parse:
Mon Dec 28 15:18:16 UTC 2020
So what went wrong?
The year is wrong because it's supposed to be uuuu (year), not YYYY (week-based-year).
The time zone is wrong because Z does support a text representation. Use VV or z instead.
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu", Locale.US);
ZonedDateTime dateTime = ZonedDateTime.parse("Mon Dec 28 15:18:16 UTC 2020", fmt);
System.out.println(dateTime);
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS")));
Output
2020-12-28T15:18:16Z[UTC]
2020-12-28 15:18:16.000
As you can see, it now parsed correctly.
The code in the question makes little sense:
It is formatting a Date value to text using toString(), just to attempt parsing that back.
It is using Optional for simple null-handling (which is discouraged), but then unconditionally calling get(), which means a null value will throw exception anyway.
The code should be:
record.getCustomerAudit().getCreated().getDate().toInstant()
This of course makes the entire question moot.
Works fine for me.
String s = "Mon Dec 28 15:18:16 UTC 2020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV yyyy",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(s, formatter);
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
System.out.println(zdt.format(formatter));
Output is
2020-12-28 15:18:16.000
Am I missing something?
Have you tried with SimpleDateFormat?
String dateString = "Mon Dec 28 15:18:16 UTC 2020";
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
System.out.println(output.format(input.parse(dateString)));
With timezone:
String dateString = "Mon Dec 28 15:18:16 UTC 2020";
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd z HH:mm:ss.SSS");
input.setTimeZone(TimeZone.getTimeZone("UTC"));
output.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(output.format(input.parse(dateString)));

Changing date format in Android getting ParseException [duplicate]

This question already has answers here:
Java - Unparseable date
(3 answers)
how to parse output of new Date().toString()
(4 answers)
Closed 2 years ago.
I'm new in Android and Java development.
I have this day type "Fri Jan 27 00:00:00 GMT+00:00 1995". <-- (input)
I want to get "1995/27/01" <-- (output)
I'm using this code :
String inputPattern = "EEE MMM dd HH:mm:ss z yyyy";
String outputPattern = "yyyy-MM-dd";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = inputFormat.parse("Fri Jan 27 00:00:00 GMT+00:00 1995");
String str = outputFormat.format(date);
but I get a ParseException.
Any idea why?
If you were using java.time (available from Java 8), you could do it like this:
public static void main(String[] args) {
// example input String
String datetime = "Fri Jan 27 00:00:00 GMT+00:00 1995";
// define a pattern that parses the format of the input String
String inputPattern = "EEE MMM dd HH:mm:ss O uuuu";
// define a formatter that uses this pattern for parsing the input
DateTimeFormatter parser = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
// use the formatter in order to parse a zone-aware object
ZonedDateTime zdt = ZonedDateTime.parse(datetime, parser);
// then output it in the built-in ISO format once,
System.out.println("date, time and zone (ISO):\t"
+ zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// then extract the date part
LocalDate dateOnly = zdt.toLocalDate();
// and output that date part using a formatter with a date-only pattern
System.out.println("date only as desired:\t\t"
+ dateOnly.format(DateTimeFormatter.ofPattern("uuuu/dd/MM")));
}
The output of this piece of code is
date, time and zone (ISO): 1995-01-27T00:00:00Z
date only as desired: 1995/27/01
Maybe add applyPattern function in code
String inputPattern = "EEE MMM dd HH:mm:ss z yyyy";
String outputPattern = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(inputPattern);
Date date = sdf.parse("Fri Jan 27 00:00:00 GMT+00:00 1995");
sdf.applyPattern(outputPattern);
String str = sdf.format(date);

Format date in Android

I have an Android app that parses a RSS feed. The "date" item returns the date in this format: "Mon, 16 Jun 2014 14:31:00 +0000". How can I convert this to the default device format?
Use simpleDateFormat
Something like:
SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy hh:mm:ss Z")
First parse this to a Date object
String str = "Mon, 16 Jun 2014 14:31:00 +0000";
Date date = new SimpleDateFormat("E, d, M yyyy H:m:s Z", Locale.ENGLISH).parse(str);

Java how to pass the timeformat in java "Fri Jan 24 12:22:13 +0000 2014"

I have got the following created date "Fri Jan 24 12:22:13 +0000 2014" from twitter , but when it comes to parsing , the goes to unparsable exception error at "z"
Would you please tell em what is the correct time format ?
The below is my code
String dateString = fullS.substring(0, 11) + " "+ year;
String timeZoneHK = content.getTimeZone();
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat outputDf = new SimpleDateFormat("HH:mm:ss EEE MMM dd yyyy");
Date date;
try {
TimeZone timezone = null;
date = inputDf.parse(dateString);
if(timeZoneHK.equals("Hong Kong")){
timezone = TimeZone.getTimeZone("Asia/Hong_Kong");
}
outputDf.setTimeZone(timezone);
String result =outputDf.format(date);
//System.out.println(outputDf.format(date));
viewHolder.txtDate.setText(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Exception
01-24 22:10:30.061: W/System.err(12573): java.text.ParseException: Unparseable date: "Fri Jan 24 13:37:08 +0000 2014" (at offset 0)
Use complete date String "Fri Jan 24 12:22:13 +0000 2014" if wanted to apply the specified format. And change z to Z:
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
Refer to: SimpleDateFormat
Z - time zone (RFC 822) - (Time Zone) Z/ZZ/ZZZ:-0800 - ZZZZ:GMT-08:00 ZZZZZ:-08:00
Joda-Time
This kind of work is much easier with the third-party open-source date-time library, Joda-Time.
Here is some example code using Joda-Time 2.3.
String input = "Fri Jan 24 12:22:13 +0000 2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss Z yyyy" );
// Parse as UTC/GMT (no time zone offset) so we may conveniently compare to input.
DateTime dateTimeUtc = formatter.withZone( DateTimeZone.UTC ).parseDateTime( input );
// Convert to Hong Kong time zone.
DateTime dateTimeHongKong = dateTimeUtc.toDateTime( DateTimeZone.forID( "Asia/Hong_Kong" ) );
Dump to console…
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeHongKong: " + dateTimeHongKong );
When run…
dateTimeUtc: 2014-01-24T12:22:13.000Z
dateTimeHongKong: 2014-01-24T20:22:13.000+08:00
Back To Date
If you need a java.util.Date for other purposes, convert your DateTime.
java.util.Date date = dateTime.toDate();

Categories