Android: How to Convert String to Date

Android: How can I Convert String to Date?

From String to Date

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}

From Date to String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {
Date date = new Date();
String dateTime = dateFormat.format(date);
System.out.println("Current Date Time : " + dateTime);
} catch (ParseException e) {
e.printStackTrace();
}

How Convert String to datetime in android

You can use SimpleDateFormat for parsing String to Date.

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
try {
Date d = sdf.parse("20130526160000");
} catch (ParseException ex) {
Log.v("Exception", ex.getLocalizedMessage());
}

Now you can convert your Date object back to String in your required format as below.

sdf.applyPattern("dd MMM yyyy hh:mm");
System.out.println(sdf.format(d));

android: how to convert a string to Date

That error is telling you that the function you are calling can throw a specific exception and you are not catching it (dateFormat.parse(...) can throw a ParseException error if the string cannot be parsed).

Try something like this

try {
DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
Date date = dateFormat.parse("Jul 20, 2018");
}
catch(ParseException pe ) {
// handle the failure
}

Android convert string to date changes the whole datetime

I don't understand why parsing a string into date changes the time?

format() will convert a date(which has no timezone, it is the number of milliseconds passed since 1970-01-01 00:00:00 UTC) into a string representation in the timezone you specified, in this case, Kuwait.

So the first time you get a String in Kuwait timezone and just print it. This is just a string with no time zone info. But the time is Kuwait time.

Then you convert the string into a date using parse() which is assuming that the date is in Kuwait time as sdf instance is same. Now this string is converted to a date and System.out.println prints it in your local timezone.

Thing to note is that both time are same just different timezones.

If you want same times, you need to create a new instance of SimpleDateFormat and pass the date string to it. So that it would assume that this is the local time zone date and parse to return a date which when printed will again give the same value. However note that this date isn’t the same as previous one, just the time is same.

Do like this

Date currentTrueSystemDate = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kuwait"));
String newConvertedDate = sdf.format(currentTrueSystemDate.getTime());
System.out.println(newConvertedDate);
try {
sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
Date newConvertedDate2 = sdf.parse(newConvertedDate);
System.out.println(newConvertedDate2);
} catch (ParseException e) {
System.out.println(e.getLocalizedMessage());
}

Convert String Date to Date in Android (Java/Kotlin) without having to deal with Call requires API level 26

You could start using desugaring so you can use java 8 methods in lower min apis
not only do you get LocalDate you get lots of other stuff too.
https://developer.android.com/studio/write/java8-support#library-desugaring

Android how to convert string into datetime format?

The pattern is actually wrong, try this

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = dateFormat.parse(fecha);

Convert the string of date and time (2018-04-13T20:00:00.0400) into date string (April 13, 2018) in Kotlin

tl;dr

Use modern java.time classes, never the terrible legacy classes.

Here is Java syntax (I have not yet learned Kotlin).

LocalDateTime                             // Represent a date with time-of-day but lacking offset-from-UTC or time zone. As such, this does *not* represent a moment, is *not* a point on the timeline.
.parse( "2018-04-13T20:00:00.0400" ) // Parse an input string in standard ISO 8601 format. Returns a `LocalDateTime` object.
.toLocalDate() // Extract the date-only portion without the time-of-day. Still no time zone or offset-from-UTC. Returns a `LocalDate` object.
.format( // Generate text representing the value of that `LocalDate` object.
DateTimeFormatter // Define a pattern to use in generating text.
.ofLocalizedDate( FormatStyle.LONG ) // Automatically localize, specifying how long/abbreviated…
.withLocale( Locale.US ) // … and what human language and cultural norms to use in localizing.
) // Return a `String`.

April 13, 2018

For earlier Android, see bullets at bottom below.

Use java.time

convert the DateTime string like "2018-04-13T20:00:00.0400" into "April 13, 2018".

You are using terrible old date-time classes that were supplanted years ago by the java.time classes.

First, parse your input string. But what is that .0400 on the end? Perhaps a fractional second? But conventionally the milliseconds, microseconds, or nanoseconds are displayed in groups of 3 digits. So your four digits here is odd. Perhaps an offset-from-UTC? Four digits is right for that, for hours and minutes with leading zero. But there is no plus or minus sign to indicate ahead-of or behind UTC. So I'll go with the fractional second.

Your input lacks any indicator of offset-from-UTC or time zone. So parse as a LocalDateTime. Your string is in standard ISO 8601 format. The standard formats are used by default in the java.time classes.

String input = "2018-04-13T20:00:00.0400";
LocalDateTime ldt = LocalDateTime.parse( input );

ldt.toString(): 2018-04-13T20:00:00.040

Extract the date portion.

LocalDate ld = ldt.toLocalDate() :

ld.toString(): 2018-04-13

Generate text representing that date's value. Let java.time automatically localize. To localize, specify:

  • FormatStyle to determine how long or abbreviated should the string be.
  • Locale to determine:

    • The human language for translation of name of day, name of month, and such.
    • The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Code:

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG ).withLocale( Locale.US );
String output = ld.format( f );

April 13, 2018

Beware: A LocalDateTime object is not a moment, is not a point on the timeline. Lacking any offset-from-UTC or time zone means it represent a range of potential moments, along a range of about 26-27 hours (the current range of time zones around the globe). If the input string were implicitly intended to represent a moment in the wall-clock time of some region, you should apply a ZoneId to get a ZonedDateTime object before extracting a LocalDate. This has been shown many times before on Stack Overflow.


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, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • 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.

How can I convert year-month-day string of date, to day as a string in user local language

I've managed to solve my question using another similar approach.

//Get user local language
var currentLang = Locale.getDefault().language

val dateString = "2021-01-24"
val parsedDate = LocalDate.parse(dateString)

val dateAsDayOfWeek = parsedDate.dayOfWeek.getDisplayName(TextStyle.FULL, Locale(currentLang))

Log.d("Date", dateAsDayOfWeek)

//Logs -> "sunday" if local language is English, "domingo" if local is Spanish, etc...


Related Topics



Leave a reply



Submit