How to split the full date format in date and time? - java

I have a lot of Strings in the format shown my example that I have to parse. I'm trying to determine which of the Strings are today.
My problem is, that the time is almost there and I just need to compare that date.
Next I want to check if time is between two timestamps "HH:mm:ss" with .after and .before, but there is the problem, that the date is almost there.
How do I split that parsed format in date and time to handle each in its own way?
I'm working in Android Studio, if that's relevant.
String dtStart = "2016-05-23 07:24:59";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if (new Date().equals(format.parse(dtStart)) ) System.out.println("true");
else System.out.println("false");
list.add(new LatLng(lat, lng));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

java.time
Use the java.time classes built into Java 8 and later.
Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport, and further adapted to Android in ThreeTen-ABP.
String dateToParse = "2016-05-23 07:24:59";
LocalDateTime dateTime = LocalDateTime.parse(dateToParse, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDate localDate = dateTime.toLocalDate();
LocalTime localTime = dateTime.toLocalTime();
// Compare here to your date & time

You can easily achieve it by using the SimpleDateFormat like that:
//Houres - seconds
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Years - days
Date hoursAndMinutes = timeFormat.parse(dtStart);
Date yearsMonthsDays = dateFormat.parse(dtStart);
That way, you only get the hours, minutes and seconds of your date.
Then, you can do the same for just the year and month and compare it afterwards.

And just to be complete, here's how you'd do it using the Joda date time library and the toLocalDate() and toLocalTime() method.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime today = new DateTime();
DateTime start = formatter.parseDateTime(dtStart);
if (today.toLocalDate().compareTo(start.toLocalDate()) != 0) {
System.out.println("true");
} else {
System.out.println("false");
}
if (today.toLocalTime().compareTo(start.toLocalTime()) > 0) {
...
}

thx for help and sry i forgot to say i'm on android studio..
i found my solution here: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
String dtStart = "2016/05/23 07:24:59";
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date dtStartOK = format.parse(dtStart);
String stringDate = DateFormat.getDateTimeInstance().format(dtStartOK);
System.out.println(stringDate);
System.out.println(DateFormat.getDateInstance().format(dtStartOK));
System.out.println(DateFormat.getTimeInstance().format(dtStartOK));
} catch (ParseException e) {
//Handle exception here, most of the time you will just log it.
e.printStackTrace();
}
gives me:
23.05.2016 07:24:59
23.05.2016
07:24:59

Related

Changing date formats

I have the following code:
// OLD DATE
String date = "Mon, 06/07";
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = date.substring(date.length() - 5);
Date dateOld;
try {
dateOld = df.parse(strDate);
} catch (Exception e) {
e.printStackTrace();
}
String dateStr = df.format(dateOld);
MonthDay monthDay = MonthDay.parse(dateStr, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime dateNew = ZonedDateTime.now().with(monthDay);
// NEW DATE
System.out.println(dateNew.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T00:00:00Z'")));
Basically what I am trying to do is change Mon, 06/07 format to this format 2021-06-07T00:00:00Z.
What I have works, but it is really terrible. What would be a better way of doing it?
This is a little tricky as you need to make some assumptions
The year, as it's not specified in the original format
TimeZone, as it's not specified at all (the final output seems to point to UTC)
The first thing your need to do, is parse the String input into a LocalDate (you could just go straight to ZonedDate, but this is where I started)
String date = "Mon, 06/07";
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.appendPattern("E, M/d")
.parseDefaulting(ChronoField.YEAR, 2021)
.toFormatter(Locale.US);
LocalDate ld = LocalDate.parse(date, parseFormatter);
Then you need to convert that to LocalDateTime
LocalDateTime ldt = ld.atStartOfDay();
And then, to a ZonedDateTime. Here' I've assumed UTC
//ZoneId zoneId = ZoneId.systemDefault();
//ZonedDateTime zdt = ldt.atZone(zoneId);
OffsetDateTime zdt = ldt.atOffset(ZoneOffset.UTC);
And finally, format the result to your desired format
String formatted = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(formatted);
Which, for me, prints...
2021-06-07T00:00:00Z
A lot of time and effort has gone into the new Date/Time APIs and you should make the time to try and learn them as best you can (I'm pretty rusty, but with a little tinkering, got to a result)
Maybe start with Date/Time trails
A solution use Calendar, Date and SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM/dd", Locale.getDefault());
try {
Date oldDate = sdf.parse("Mon, 06/07");
Calendar calendar = Calendar.getInstance();
int savedYear = calendar.get(Calendar.YEAR);
if (oldDate != null) {
calendar.setTime(oldDate);
calendar.set(Calendar.YEAR, savedYear);
sdf.applyPattern("yyyy-MM-dd'T00:00:00Z'");
System.out.println(sdf.format(calendar.getTime()));
}
} catch (ParseException e) {
e.printStackTrace();
}

Formatting a String date into a different format in Java

I am trying to format a JSON which has a date key in the format:
date: "2017-05-23T06:25:50"
My current attempt is the following:
private String formatDate(String date) {
SimpleDateFormat format = new SimpleDateFormat("MM/DD/yyyy");
String formattedDate = "";
try {
formattedDate = format.format(format.parse(String.valueOf(date)));
} catch (ParseException e) {
e.printStackTrace();
}
return formattedDate;
}
But in this occasion, the result isn't shown in my app, the TextView is invisible and I couldn't log anything.
I really tried other solutions, but no success for me. I don't know if it's because the incoming value is a string.
Use this code to format your `2017-05-23T06:25:50'
String strDate = "2017-05-23T06:25:50";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(strDate);
SimpleDateFormat sdfnewformat = new SimpleDateFormat("MMM dd yyyy");
String finalDateString = sdfnewformat.format(convertedDate);
} catch (ParseException e) {
e.printStackTrace();
}
The converted finalDateString set to your textView
This will work for you.
String oldstring= "2017-05-23T06:25:50.0";
Date datee = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(oldstring);
This code worked for me :
public static String getNewsDetailsDateTime(String dateTime) {
#SuppressLint("SimpleDateFormat") DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = null;
try {
date = format.parse(dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
#SuppressLint("SimpleDateFormat") String strPublishDateTime = new SimpleDateFormat("MMM d, yyyy h:mm a").format(date);
return strPublishDateTime;
}
Out put format was : Dec 20 , 2017 2.30 pm.
Use this function :
private String convertDate(String dt) {
//String date="2017-05-23T06:25:50";
try {
SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); //date format in which your current string is
Date newDate = null;
newDate = spf.parse(dt);
spf = new SimpleDateFormat("MM/DD/yyyy"); //date format in which you want to convert
dt = spf.format(newDate);
System.out.println(dt);
Log.e("FRM_DT", dt);
} catch (ParseException e) {
e.printStackTrace();
}
return dt;
}
TL;DR
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("MM/dd/uuuu");
private static String formatDate(String date) {
return LocalDateTime.parse(date).format(DATE_FORMATTER);
}
Now formatDate("2017-05-23T06:25:50") returns the desired string of 05/23/2017.
java.time
In 2017 I see no reason why you should struggle with the long outdated and notoriously troublesome SimpleDateFormat class. java.time, the modern Java date and time API also known as JSR-310, is so much nicer to work with.
Often when converting from one date-time format to another you need two formatters, one for parsing the input format and one for formatting into the output format. Not here. This is because your string like 2017-05-23T06:25:50 is in the ISO 8601 format, the standard that the modern classes parse as their default, that is, without an explicit formatter. So we only need one formatter, for formatting.
What went wrong in your code
When I run your code, I get a ParseException: Unparseable date: "2017-05-23T06:25:50". If you didn’t notice the exception already, then you have a serious flaw in your project setup that hides vital information about errors from you. Please fix first thing.
A ParseException has a method getErrorOffset (a bit overlooked), which in this case returns 4. Offset 4 in your string is where the first hyphen is. So when parsing in the format MM/DD/yyyy, your SimpleDateFormat accepted 2017 as a month (funny, isn’t it?), then expected a slash and got a hyphen instead, and therefore threw the exception.
You’ve got another error in your format pattern string: Uppercase DD is for day-of-year (143 in this example). Lowercase dd should be used for day-of-month.
Question: Can I use java.time on Android?
Yes you can. It just requires at least Java 6.
In Java 8 and later the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).
On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310, where the modern date and time API was first described.
Try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dt));
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
String output = sdf1.format(c.getTime());

String date into Epoch time

I am little bit confused in dates. I am currently working on the weather app and everything works fine .. I just wanna handle this type of format into my own desirable format.
2017-09-10T18:35:00+05:00
I just wanna convert this date into Epoch Time and then I settle the date in my desire format ::
for J-SON
or i wanna convert this date into less figure i.e Sun , 9 september 9:23 Am etc.
http://dataservice.accuweather.com/currentconditions/v1/257072?apikey=JTgPZ8wN9VUy07GaOODeZfZ3sAM12irH&language=en-us&details=true
ThreeTenABP
The other answers are correct, but outdated before they were written. These days I recommend you use the modern Java date and time API known as JSR-310 or java.time. Your date-time string format is ISO 8601, which the modern classes “understand” as their default.
Can you use the modern API on Android yet? Most certainly! The JSR-310 classes have been backported to Android in the ThreeTenABP project. All the details are in this question: How to use ThreeTenABP in Android Project.
long epochTime = OffsetDateTime.parse("2017-09-10T18:35:00+05:00")
.toInstant()
.getEpochSecond();
The result is 1505050500.
Edit: Arvind Kumar Avinash correctly points out in a comment: You do not need to convert an OffsetDateTime to an Instant to get the epoch seconds. You can simply use OffsetDateTime#toEpochSecond.
Example of how to convert this into a human-readable date and time:
String formattedDateTime = Instant.ofEpochSecond(epochTime)
.atZone(ZoneId.of("Africa/Lusaka"))
.format(DateTimeFormatter.ofPattern("EEE, d MMMM h:mm a", Locale.ENGLISH));
This produces Sun, 10 September 3:35 PM. Please provide the correct region and city for the time zone ID you want. If you want to rely on the device’s time zone setting, use ZoneId.systemDefault(). See the documentation of DateTimeFormatter.ofPattern() for the letters you may use in the format pattern string, or use DateTimeFormatter.ofLocalizedDateTime() for one of your locale’s default formats.
Use a SimpleDateFormat instance to parse the string into a Date object:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = parser.parse("2017-09-10T18:35:00+05:00");
And then use another SimpleDateFormat to display it:
DateFormat format = new SimpleDateFormat("EEE, dd MMMMM h:mm a");
String formatted = format.format(date); // Sun, 10 September 1:35 PM
You can use SimpleDate formatter to parse you date as string into epoch
String input = "2017-09-10T18:35:00+05:00";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
Date date = sf.parse(input);
long dateInEpochFormatInMilliSeconds = date.getTime();
//if you want this in seconds then
long dateInEpochFormatInSeconds = date.getTime()/1000L;
//if you want to show only date month and year then
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String date = sdf.format(dateInEpochFormatInMilliSeconds);
//This date String will contain the date in dd-MM-yyyy format
} catch (ParseException| ArithmeticException e) {
e.printStackTrace();
}
String time_at_which_weather_capture = "Time : ";
DateFormat dateFormat = new SimpleDateFormat("EEE,d M yyyy h:MM a");
long timeInMillieSec = 0 ;
try {
Date date = dateFormat.parse(readyToUpdate.getTime());
timeInMillieSec = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
time.setText(time_at_which_weather_capture + String.valueOf(time_fetcher(timeInMillieSec)));
public String time_fetcher (long time_coming_to_its_original_form) {
Date date = new Date (time_coming_to_its_original_form);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d M yyyy h:MM a");
return sdf.format(date);
}

Date format Error(Month conflict) [duplicate]

This question already has answers here:
Getting wrong month when using SimpleDateFormat.parse
(3 answers)
Closed 5 years ago.
I am trying to convert string of format yyyy-mm-dd to dd-MMM-yy. I am getting correct year and days but for month it is showing only jan irrespective of my input. How to fix it?
String input = "2013-09-14";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-mm-dd");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yy");
Date date = null;
try {
date = format1.parse(input);
String temp = format2.format(date);
System.out.println(temp);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Output:
14-Jan-13
But I should get:
14-Oct-13
mm is for minute
you need MM or MMM for month.
See SimpleDateFormat for reference.
mm is for minutes. MM is for months.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
I would suggest latest API LocalDate which not requires try/catch and which is easier to use :
String input = "2013-09-14";
LocalDate inputDate = LocalDate.parse(input, DateTimeFormatter.ISO_DATE);
String format = inputDate.format(DateTimeFormatter.ofPattern("dd-MMM-yy"));
System.out.println(format);
DateTimeFormatter.ISO_DATE is shortcut for DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate inputDate = LocalDate.parse(input); would also work because ISO_DATE the default format
DateTimeFormatter doc (patterns)
The pattern is case sensitive:
MM is month, mm is Minute:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
For more Information read The javadoc of SimpleDateFormat
personally i used a pattern to do this,
LocalTime w = LocalTime.MIDNIGHT.plus(d);
s = DateTimeFormatter.ofPattern("HH:mm:ss").format(w);
and i advise you to use java 8 date type instead

Java Get One Day Before Specific Date

I have a String expired date. But I need to perform some SQL statement the day before expired date falls. I get my expired date and by:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String expiredDate = null;
String currentDate = dateFormat.format(new Date());
Calendar cal = Calendar.getInstance();
try {
cal.setTime(dateFormat.parse(loanDate));
cal.add(Calendar.WEEK_OF_YEAR, 2);
expiredDate = dateFormat.format(cal.getTimeInMillis());
cal.add(Calendar.WEEK_OF_YEAR, -2);
} catch (ParseException e) {
e.printStackTrace();
}
Then, I got an if statement to perform SQL statement:
if(expiredDate.equals(currentDate)){
promptExtensionDialog();
}
What I am trying to achieve is for the if statement, instead of the expiredDate itself, I need to get one day before the expired date and compare with the current date. I wonder how to achieve this?
Thanks in advance.
EDIT
try {
cal.setTime(dateFormat.parse(expiredDate));
cal.add(Calendar.DATE, -1);
expiredDate = dateFormat.format(cal.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(LoanBook.this,
expiredDate, Toast.LENGTH_LONG)
.show();
This returns me the next date instead of previous date. Do you have any ideas?
Using Java's (pre-8) built-in Date and Time API will eat you alive. Use JodaTime for complex DateTime manipulations.
Getting the previous day is as simple as this.
DateTime dateTime = new DateTime();
System.out.println(dateTime);
System.out.println(dateTime.minusDays(1));
If you don't want any external libraries:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2014-10-28";
Date date = sdf.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
Date yesterday = calendar.getTime();
System.out.println(yesterday);
System.out.println(date);
Have you tried JodaTime? It is a fantastic library to do date manipulation easily. In fact, a lot of Java 8 date handling are derived from JodaTime.
For your needs, you could do something like:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dt = formatter.parseDateTime(expiredDate);
DateTime dayBefore = dt.minusDays(1);
The other two answers are basically correct. But they omit the crucial issue of time zones and start of day. If you want all of yesterday, do something like the following.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime yesterdayStart = now.minusDays( 1 ).withTimeAtStartOfDay();
Convert to a java.sql.Timestamp.
java.sql.Timestamp ts = new java.sql.Timestamp( yesterdayStart.getMillis() );

Categories

Resources