Split date/time strings - java

I have a ReST service which downloads information about events in a persons calendar...
When it returns the date and time, it returns them as a string
e.g. date = "12/8/2012" & time = "11:25 am"
To put this into the android calendar, I need to do the following:
Calendar beginTime = Calendar.getInstance();
beginTime.set(year, month, day, hour, min);
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);
How can I split the date and time variables so that they are useable in the "beginTime.set() " method?

I don't thinks you really need how to split the string, in your case it should be 'how to get time in milliseconds from date string', here is an example:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
String date = "12/8/2012";
String time = "11:25 am";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try {
Date dt = df.parse(date + " " + time);
Calendar ca = Calendar.getInstance();
ca.setTime(dt);
System.out.println(ca.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
}
}

Try this:
String date = "12/8/2012";
String time = "11:25 am";
String[] date1 = date.split("/");
String[] time1 = time.split(":");
String[] time2 = time1[1].split(" "); // to remove am/pm
Calendar beginTime = Calendar.getInstance();
beginTime.set(Integer.parseInt(date1[2]), Integer.parseInt(date1[1]), Integer.parseInt(date1[0]), Integer.parseInt(time1[0]), Integer.parseInt(time2[0]));
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);
Hope this helps.

Assuming you get your date in String format (if not, convert it!) and then this:
String date = "12/8/2012";
String[] dateParts = date.split("/");
String day = dateParts[0];
String month = dateParts[1];
Similarly u can split time as well!

You can see an example of split method here : How to split a string in Java
Then simply use the array for your parameter eg: array[0] for year and etc..

Use SimpleDateFormat (check api docs). If you provide proper time pattern it will be able to convert string into Date instantly.

This is just a Idea, you can do some thing like this without splitting
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
Date date = formatter.parse("12/8/2012 11:25 am");
Calendar cal=Calendar.getInstance();
cal.setTime(date);

java.time either through desugaring or through ThreeTenABP
Consider using java.time, the modern Java date and time API, for your date and time work. With java.time it’s straightforward to parse your two strings for date and time individually and then combine date and time into one object using LoalDate.atTime().
The way I read your code you are really after a count of milliseconds since the epoch. So this is what I am giving you in the first snippet. Feel free to take it apart and use only the lines you need.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h:mm a")
.toFormatter(Locale.ENGLISH);
String dateString = "12/8/2012";
String timeString = "11:25 am";
LocalDate date = LocalDate.parse(dateString, dateFormatter);
LocalTime time = LocalTime.parse(timeString, timeFormatter);
long startMillis = date
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
System.out.println(startMillis);
When running in my time zone (at UTC offset +02:00 in August) the output is:
1344763500000
For anyone reading along that does need the individual numbers from the two strings, getting those is straightforward too. For example:
int year = date.getYear();
Month month = date.getMonth();
int monthNumber = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
int hourOfDay = time.getHour();
int hourWithinAmOrPm = time.get(ChronoField.HOUR_OF_AMPM);
int minute = time.getMinute();
System.out.format("Year %d month %s or %d day %d hour %d or %d AM/PM minute %d%n",
year, month, monthNumber, dayOfMonth, hourOfDay, hourWithinAmOrPm, minute);
Year 2012 month AUGUST or 8 day 12 hour 11 or 11 AM/PM minute 25
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Related

How to parse "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" date format to simple in Android? [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 4 years ago.
How do I can parse this date 2018-01-09T11:11:02.0+03:00 to dd.MM.yyyy hh:mm format in Android?
And what does T between 09 and 11 mean?
Thanks.
I don't know how the back-end developer got this format.
I am using Java.
You can do this with SimpleDateFormat.
Here is a tested example in Java:
String dateString = "2018-01-09T11:11:02.0+03:00";
String inPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
String outPattern = "dd.MM.yyyy hh:mm";
SimpleDateFormat inFormat = new SimpleDateFormat(inPattern, Locale.getDefault());
SimpleDateFormat outFormat = new SimpleDateFormat(outPattern, Locale.getDefault());
try {
Date inDate = inFormat.parse(dateString);
String outDate = outFormat.format(inDate);
Log.e("TEST", outDate);
} catch (ParseException e) {
e.printStackTrace();
}
Here is a tested example in Kotlin:
val dateString = "2018-01-09T11:11:02.0+03:00"
val inPattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
val outPattern = "dd.MM.yyyy hh:mm"
val inFormat = SimpleDateFormat(inPattern, Locale.getDefault())
val outFormat = SimpleDateFormat(outPattern, Locale.getDefault())
val inDate = inFormat.parse(dateString)
val outDate = outFormat.format(inDate)
Log.e("TEST", outDate)
If you are using java, you can use SimpeDateFormat with patterns:
String date = "2018-01-09T11:11:02.0+03:00";
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
SimpleDateFormat output = new SimpleDateFormat("dd.MM.yyyy hh:mm");
Date d = null;
try {
d = dateformat.parse(date /*your date as String*/);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = output.format(d);
Log.d("Date format", "output date :" + formattedDate);
The output is :
D/Date format: output date :09.01.2018 09:11
EDIT : Thanks to #OleV.V., for API > 26, or using ThreeTenABP we can use
DateTimeFormatter, we can do something like that
String date = "2018-01-09T11:11:02.0+03:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
DateTimeFormatter formatterOut = DateTimeFormatter.ofPattern("dd.MM.yyyy hh:mm");
LocalDate parsedDate = LocalDate.parse(date, formatter);
String formattedDate = formatterOut.format(parsedDate);
Log.d("Date format", "output date :" + formattedDate);
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
String backendDateTimeString = "2018-01-09T11:11:02.0+03:00";
OffsetDateTime dateTime = OffsetDateTime.parse(backendDateTimeString);
String presentationDateTimeString = dateTime.format(desiredFormatter);
System.out.println(presentationDateTimeString);
This prints:
09.01.2018 11:11
Please note: I am using uppercase HH in the format pattern string. This indicates hour of day from 00 through 23. In the question you used lowercase hh, which in a format pattern string means hour with AM or PM from 01 through 12, so 00:33 would come out as 12:33 and 15:47 as 03:47. I didn’t think you intended this.
The format that your backend developer got, 2018-01-09T11:11:02.0+03:00, is ISO 8601. It’s widespread, and it’s the international standard, so it’s good that s/he got that. The funny T in the middle indicates the start of the time part to separate it from the date part. The one-arg OffsetDateTime.parse method parses ISO 8601, which is why we didn’t need any formatter for parsing. OffsetDateTime and DateTimeFormatter are classes from java.time, the modern Java date and time API.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (API level 26 and up) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages (my code was tested with these imports).
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601

How to compare two dates along with time in java

I have two Date objects with the below format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;
try {
matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);
try {
currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I want to compare the above two dates along with time.
How should I compare in Java.
Thanks
Since Date implements Comparable<Date>, it is as easy as:
date1.compareTo(date2);
As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).
Note that Date has also .after() and .before() methods which will return booleans instead.
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
An alternative is Joda-Time.
Use DateTime
DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
// Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);
if (afterSix) {
System.out.println("Go home, it's after 6 PM!");
}
else {
System.out.println("Hello!");
}
The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.
String dateTimeString = "2014-01-16T10:25:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
if (dateTime.isBefore(now)) {
System.out.println(dateTimeString + " is in the past");
} else if (dateTime.isAfter(now)) {
System.out.println(dateTimeString + " is in the future");
} else {
System.out.println(dateTimeString + " is now");
}
When running in 2020 output from this snippet is:
2014-01-16T10:25:00 is in the past
Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.
Question: For Android development doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601

How to get the weekday of a Date?

I want to get the day of week from the Java Date object when I have an array of Date in String with me.
SimpleDateFormat sourceDateformat = new SimpleDateFormat("yyyy-MM-dd");
public String[] temp_date;
public Int[] day = new Int[5];
Date[] d1= new Date[5];
Calendar[] cal= new Calendar[5]
try {
d1[i]= sourceDateformat.parse(temp_date[i].toString());
cal[i].setTime(d1[i]); // its not compiling this line..showing error on this line
day[i]= cal[i].get(Calendar.DAY_OF_WEEK);
}
catch (ParseException e) {
e.printStackTrace();
}
Does anyone know the answer to this?
You can get the day-integer like that:
Calendar c = Calendar.getInstance();
c.setTime(yourdate); // yourdate is an object of type Date
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // this will for example return 3 for tuesday
If you need the output to be "Tue" rather than 3, instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
Taken from here: How to determine day of week by passing specific date?
// kotlin
val calendar = Calendar.getInstance()
val dateInfo = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.time)
data.text = dateInfo
java.time
You can do it using DateTimeFormatter.ofPattern("EEEE"):
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).format(dtfOutput);
}
}
Output:
Friday
Alternatively, you can get it using LocalDate#getDayOfWeek:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
}
}
Output:
Friday
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.
This is one of the many things that have become a lot easier with the advent of java.time, the modern Java date and time API.
String tempDate = "2020-03-29";
LocalDate date = LocalDate.parse(tempDate);
DayOfWeek day = date.getDayOfWeek();
System.out.println(day);
Output:
SUNDAY
Of course we now have got an enum for the days of the week. There’s no longer any reason to fiddle with integers and having to remember on what day of week they begin and whether the days are numbered from 0 or 1.
I am expoiting the fact that your expected input format (yyyy-MM-dd in your code) is ISO 8601, the default for java.time, so we don’t need to specify any formatter explicitly.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
In Kotlin, just do this:
val yourDateStr = "2021-01-01"
val df = DateFormat.parse(yourDateStr)
val weedDay = df.getWeekDay(yourTimeZone)
the below code works, depending on what number you enter in the DAY_OF_WEEK, that returns the specific weekday, in this example it always returns a future date and day will always be Tuesday.
DAY_OF_WEEK
public static String getTodaysDateAndTime(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 5);
cal.add(Calendar.DAY_OF_WEEK, 2);
Date date = cal.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String futureDate = dateformat.format(date);
System.out.println(futureDate);
return futureDate;
}

the simplest way to change a time to particular timezone

there are two string
String date = "9/13/2012";
String time = "5:48pm";
the time is GMT+0, I wanna change it to GMT+8,what is the simplest way to change a time to particular timezone
Parse it using a SimpleDateFormat set to the UTC time zone
Format the parsed Date value using a SimpleDateFormat set to the time zone you're interested in. (It's likely to be something other than just "UTC+8" - you should find out which TZDB time zone ID you really want.
For example:
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy h:mma", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
Date date = inputFormat.parse(date + " " + time);
// Or whatever format you want...
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
outputFormat.setTimeZone(targetTimeZone);
String outputText = outputFormat.format(date);
(If you can use Joda Time instead, that'd be great - but I understand that it's pretty big for an Android app.)
The Joda-Time library provides a good set of objects for working with dates/times in multiple time zones. http://joda-time.sourceforge.net/
Something like this for example:
String date = "9/13/2012";
String time = "5:48pm";
String[] dateParts = date.split("/");
Integer month = Integer.parseInt(dateParts[0]);
Integer day = Integer.parseInt(dateParts[1]);
Integer year = Integer.parseInt(dateParts[2]);
String[] timeParts = time.split(":");
Integer hour = Integer.parseInt(timeParts[0]);
Integer minutes = Integer.parseInt(timeParts[1].substring(0,timeParts[1].lastIndexOf("p")));
DateTime dateTime = new DateTime(year, month, day, hour, minutes, DateTimeZone.forID("Etc/GMT"));
dateTime.withZone(DateTimeZone.forID("Etc/GMT+8"));
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*.
Also, 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.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String date = "9/13/2012";
String time = "5:48pm";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:ma", Locale.UK);
LocalDateTime ldtSource = LocalDateTime.parse(date + " " + time, dtf);
OffsetDateTime odtSource = ldtSource.atOffset(ZoneOffset.UTC);
OffsetDateTime odtTarget = odtSource.withOffsetSameInstant(ZoneOffset.of("+08:00"));
System.out.println(odtTarget);
// In a custom format
System.out.println(odtTarget.format(dtf));
}
}
Output:
2012-09-14T01:48+08:00
9/14/2012 1:48am
ONLINE DEMO
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.

Android SimpleDateFormat, how to use it?

I am trying to use the Android SimpleDateFormat like this:
String _Date = "2010-09-29 08:45:22"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = fmt.parse(_Date);
return fmt.format(date);
}
catch(ParseException pe) {
return "Date";
}
The result is good and I have: 2010-09-29
But if I change the SimpleDateFormat to
SimpleDateFormat("dd-MM-yyyy");
the problem is that I will got 03-03-0035 !!!!
Why and how to get the format like dd-MM-yyyy?
I assume you would like to reverse the date format?
SimpleDateFormat can be used for parsing and formatting.
You just need two formats, one that parses the string and the other that returns the desired print out:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(dateString);
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
Since Java 8:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
TemporalAccessor date = fmt.parse(dateString);
Instant time = Instant.from(date);
DateTimeFormatter fmtOut = DateTimeFormatter.ofPattern("dd-MM-yyyy").withZone(ZoneOffset.UTC);
return fmtOut.format(time);
Below is all date formats available, read more doc here.
Symbol Meaning Kind Example
D day in year Number 189
E day of week Text E/EE/EEE:Tue, EEEE:Tuesday, EEEEE:T
F day of week in month Number 2 (2nd Wed in July)
G era designator Text AD
H hour in day (0-23) Number 0
K hour in am/pm (0-11) Number 0
L stand-alone month Text L:1 LL:01 LLL:Jan LLLL:January LLLLL:J
M month in year Text M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
S fractional seconds Number 978
W week in month Number 2
Z time zone (RFC 822) Time Zone Z/ZZ/ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00
a am/pm marker Text PM
c stand-alone day of week Text c/cc/ccc:Tue, cccc:Tuesday, ccccc:T
d day in month Number 10
h hour in am/pm (1-12) Number 12
k hour in day (1-24) Number 24
m minute in hour Number 30
s second in minute Number 55
w week in year Number 27
G era designator Text AD
y year Number yy:10 y/yyy/yyyy:2010
z time zone Time Zone z/zz/zzz:PST zzzz:Pacific Standard
I think this Link might helps you
OR
Date date = Calendar.getInstance().getTime();
//
// Display a date in day, month, year format
//
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
System.out.println("Today : " + today);
String _Date = "2010-09-29 08:45:22"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat fmt2 = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = fmt.parse(_Date);
return fmt2.format(date);
}
catch(ParseException pe) {
return "Date";
}
try this.
Using the date-time API of java.util and their formatting API, SimpleDateFormat I have come across surprises several times but this is the biggest one! 😮😮😮
Given below is the illustration of what you have described in your question:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
class Main {
public static void main(String[] args) {
System.out.println(formatDateWithPattern1("2010-09-29 08:45:22"));
System.out.println(formatDateWithPattern2("2010-09-29 08:45:22"));
}
static String formatDateWithPattern1(String strDate) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = fmt.parse(strDate);
return fmt.format(date);
} catch (ParseException pe) {
return "Date";
}
}
static String formatDateWithPattern2(String strDate) {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = fmt.parse(strDate);
return fmt.format(date);
} catch (ParseException pe) {
return "Date";
}
}
}
Output:
2010-09-29
03-03-0035
Surprisingly, SimpleDateFormat silently performed the parsing and formatting without raising an alarm. Anyone reading this will not have a second thought to stop using them completely and switch to the modern date-time API.
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.
Using the modern date-time API:
Since the pattern used in both the functions are wrong as per the input string, the parser should raise the alarm and the parsing/formatting types of the modern date-time API do it responsibly.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
class Main {
public static void main(String[] args) {
System.out.println(formatDateWithPattern1("2010-09-29 08:45:22"));
System.out.println(formatDateWithPattern2("2010-09-29 08:45:22"));
}
static String formatDateWithPattern1(String strDate) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");
try {
LocalDateTime date = LocalDateTime.parse(strDate, dtf);
return dtf.format(date);
} catch (DateTimeParseException dtpe) {
return "Date";
}
}
static String formatDateWithPattern2(String strDate) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu");
try {
LocalDateTime date = LocalDateTime.parse(strDate, dtf);
return dtf.format(date);
} catch (DateTimeParseException dtpe) {
return "Date";
}
}
}
Output:
Date
Date
Moral of the story
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. Stop using them completely and switch to the modern date-time API. Learn about the modern date-time API at Trail: Date Time.
Stick to the format in your input date-time string while parsing it. If you want the output in a different format, use a differnt instance of the parser/formatter class.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
String strDateTime = "2010-09-29 08:45:22";
DateTimeFormatter dtfForParsing = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtfForParsing);
System.out.println(ldt);// The default format as returned by LocalDateTime#toString
// Some custom formats for output
System.out.println("########In custom formats########");
DateTimeFormatter dtfForFormatting1 = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss");
DateTimeFormatter dtfForFormatting2 = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter dtfForFormatting3 = DateTimeFormatter.ofPattern("'Day: 'EEEE, 'Date: 'MMMM dd uuuu");
System.out.println(dtfForFormatting1.format(ldt));
System.out.println(dtfForFormatting2.format(ldt));
System.out.println(dtfForFormatting3.format(ldt));
System.out.println("################################");
}
}
Output:
2010-09-29T08:45:22
########In custom formats########
29-09-2010 08:45:22
29-09-2010
Day: Wednesday, Date: September 29 2010
################################
This worked for me...
#SuppressLint("SimpleDateFormat")
private void setTheDate() {
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("MM'/'dd'/'y hh:mm");
curDate = formatter.format(curDateTime);
mDateText.setText("" + curDate);
}
java.time and desugaring
I recommend that you use java.time, the modern Java date and time API, for your date work. First define a formatter for your string:
private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
Then do:
String dateString = "2010-09-29 08:45:22";
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
String newString = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(newString);
Output is:
2010-09-29
I find it a good practice to parse the entire string even though we currently have no use for the time of day. That may come some other day. java.time furnishes a predefined formatter for your first output format, DateTimeFormatter.ISO_LOCAL_DATE. If you want the opposite order of day, month and year, we will need to write our own formatter for that:
private static DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("dd-MM-uuuu");
Then we can obtain that too:
String dmyReversed = dateTime.format(dateFormatter);
System.out.println(dmyReversed);
29-09-2010
What went wrong in your code?
the problem is that I will got 03-03-0035 !!!!
This is how confusing a SimpleDateFormat with standard settings is: With format pattern dd-MM-yyyy it parses 2010-09-29 as the 2010th day of month 9 of year 29. Year 29 AD that is. And it doesn’t disturb it that there aren’t 2010 days in September. It just keeps counting days through the following months and years and ends up five and a half years later, on 3 March year 35.
Which is just a little bit of the reason why I say: don’t use that class.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?
Wikipedia article: ISO 8601
Here is an easy example of SimpleDateFormat tried in Android Studio 3 and Java 9:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String strDate = sdf.format(strDate);
Note:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); shows
some deprecation warning in Android Studio 3 Lint. So, add a second
parameter Locale.US to specify the Localization in date formatting.
It took a lot of efforts. I did a lot of hit and trial and finally I got the solution. I had used ""MMM"" for showing month as: JAN
If you looking for date, month and year separately
or how to use letters from answer of heloisasim
SimpleDateFormat day = new SimpleDateFormat("d");
SimpleDateFormat month = new SimpleDateFormat("M");
SimpleDateFormat year = new SimpleDateFormat("y");
Date d = new Date();
String dayS = day.format(d);
String monthS = month.format(d);
String yearS = year.format(d);
public String formatDate(String dateString) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = fmt.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
}

Categories

Resources