Parse a date from a string - java

I have String like this:
String strDateTimeStamp = "2016-02-29 18:31:51";
Now I would like to extract it to get result in a below format:
String strYear = "2016";
String strMonth = "02";
String strDate = "29";
String strHour = "18";
String strMinute = "31";
String strSecond = "51";

If you are working with dates you should consider using Calendar :
String strDateTimeStamp = "2016-02-29 18:31:51";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(strDateTimeStamp);
Calendar cal = new Calendar.Builder().setInstant(date).build();
String strYear = Integer.toString(cal.get(Calendar.YEAR));
// Calendar MONTH is starting from 0 we need to add 1
String strMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
String strDate = Integer.toString(cal.get(Calendar.DATE));
String strHour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
String strMinute = Integer.toString(cal.get(Calendar.MINUTE));
String strSecond = Integer.toString(cal.get(Calendar.SECOND));

All of the Answers using java.util.Date and java.text.DateFormat/.SimpleDateFormat are outmoded. Those old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
java.time
The java.time framework is built into Java 8 and later. A vast improvement over the old date-time classes.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
First, replace the SPACE in the middle of your input string with a T to conform with the ISO 8601 standard. These standard formats are used by default in the java.time classes when parsing/generating strings.
String input = "2016-02-29 18:31:51".replace( " " , "T" );
Parse as a LocalDateTime. The “Local” means not associated with any time zone. So this is not an actual moment on the timeline. But apparently not an issue in the context of this Question.
LocalDateTime ldt = LocalDateTime.parse( input );
Now you can ask for your various pieces as needed by calling the various getter methods. These methods return an int primitive which you can, of course, convert to String values.
getYear
getMonthValue (or getMonth for Month enum))
getDayOfMonth (and getDayOfWeek for DayOfWeek enum)
getHour
getMinute
getSecond
getNano (the fraction of a second)

Try This..
String CurrentString = "2016-02-29 18:31:51";
String[] separated = CurrentString.split(" ");
String date = separated[0];
String time = separated[1];
String[] separated_date = date.split("-");
String[] separated_time = time.split(":");
String strYear = separated_date[0];
String strMonth = separated_date[1];
String strDate = separated_date[2];
String strHour = separated_time[0];
String strMinute = separated_time[1];
String strSecond = separated_time[2];

You can do like this by splitting your String
String[] splittedString = strDateTimeStamp.split("-|:|\\s");
String strYear = splittedString[0];
String strMonth = splittedString[1];
String strDate = splittedString[2];
String strHour = splittedString[3];
String strMinute = splittedString[4];
String strSecond = splittedString[5];

First split string using split(" ") on the basis of space ..it will give you a array of string of length 2 . which contains (2016-03-04) and (16:32:33) . Then split both string againg using split("-") and split(":") reapectively . you will get your answer. Please try code at your own may better to you.

I suggest to use regex with a pattern like "[- :]"
Example:
public static void main(String[] args) {
String strDateTimeStamp = "2016-02-29 18:31:51";
String[] solution = strDateTimeStamp.split("[- :]");
for (int i = 0; i < solution.length; i++) {
System.out.println(solution[i]);
}
}
this will generate an array with all the elements you need

String strDateTimeStamp = "2016-02-29 18:31:51";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(strDateTimeStamp);
Calendar cal = new Calendar.Builder().setInstant(date).build();
String strYear = Integer.toString(cal.get(Calendar.YEAR));
// Calendar MONTH is starting from 0 we need to add 1
String strMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
String strDate = Integer.toString(cal.get(Calendar.DATE));
String strHour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
String strMinute = Integer.toString(cal.get(Calendar.MINUTE));
String strSecond = Integer.toString(cal.get(Calendar.SECOND));

Related

Java String to date parsing error, how to do it properly

I am interested to know if my code is correct and it doesn't have any issues. Date is taken from binary file, written as a string in such format YYYY-MM-DD/Hours-minutes-seconds example: 2022-01-23/12:00:00.
Program was meant to check date if it's expiring or expired, add it to proper list and display it after loops end.
public static void expiration_date(String filepath){
try {
DataInputStream read = new DataInputStream(new FileInputStream(filepath));
DateTimeFormatter format_day = DateTimeFormatter.ofPattern("uuuu/MM/dd");
DateTimeFormatter format_hour = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDate now_day = LocalDate.now();
LocalDateTime now_hour = LocalDateTime.now();
ArrayList<String> dates = new ArrayList<>();
ArrayList<String> expire_in_week = new ArrayList<>();
ArrayList<String> expire_tomorrow = new ArrayList<>();
ArrayList<String> expire_today = new ArrayList<>();
ArrayList<String> expired = new ArrayList<>();
while(read.available()>0) {
String name = read.readUTF();
String surname = read.readUTF();
String date = read.readUTF();
String cardcode = read.readUTF();
String cardtype = read.readUTF();
int contract_num = read.readInt();
String cert_num = read.readUTF();
String phone_num = read.readUTF();
String email = read.readUTF();
String status = read.readUTF();
String comment = read.readUTF();
dates.add(date);
for (String s:dates){
String[] data = s.split("/");
String days =data[0];
LocalDate date_days = LocalDate.parse(days.replace("-", "/"), format_day);
String hours =data[1];
LocalTime date_hours = LocalTime.parse(hours.replace("-", ":"),format_hour);
long daysbetween = ChronoUnit.DAYS.between(now_day,date_days);
long hoursbetween = ChronoUnit.HOURS.between(now_hour,date_hours);
if (daysbetween==7){
expire_in_week.add(cert_num);
}else if (daysbetween==1){
expire_tomorrow.add(cert_num);
}else if (daysbetween==0 && hoursbetween>0){
expire_today.add(cert_num);
}else if (daysbetween<0 || (daysbetween==0 && hoursbetween<0)){
expired.add(cert_num);
}else{}
}
}
System.out.println("Certificates that expires:");
System.out.println("Next week");
for (String w:expire_in_week){
System.out.print(w+"|");
}
System.out.println("Tomorrow");
for (String tm:expire_tomorrow){
System.out.print(tm+"|");
}
System.out.println("Today");
for (String td:expire_today){
System.out.print(td+"|");
}
System.out.println("Today");
for (String ex:expired){
System.out.print(ex+"|");
}
}catch(FileNotFoundException ex){ex.printStackTrace();}
catch(IOException ex){ex.printStackTrace();}
}
When i start it i got error message returned:
Exception in thread "main" java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 12:00 of type java.time.LocalTime
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:463)
at java.base/java.time.LocalDateTime.until(LocalDateTime.java:1677)
at java.base/java.time.temporal.ChronoUnit.between(ChronoUnit.java:272)
at com.company.program.expiration_date(program.java:189)
at com.company.program.main(program.java:364)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 12:00 of type java.time.LocalTime
at java.base/java.time.LocalDate.from(LocalDate.java:398)
at java.base/java.time.LocalDateTime.from(LocalDateTime.java:458)
... 4 more
The issue is because date_hours is of type LocalDateTime and date_hours is of type LocalTime. Try using the same type for both.
LocalTime now_hour = LocalTime.now();
Side note to parse the values of LocalDate and LocalTime you can try this
String data = "2022-01-23/12-00-00";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd/HH-mm-ss");
LocalDate dateDays = LocalDate.parse(data, dateTimeFormatter);
LocalTime dateHours = LocalTime.parse(data, dateTimeFormatter);
See working example of your code here: https://github.com/RobbingDaHood/answers/blob/master/so70824574/src/Main.java
You LocalTime date_hours needs a timezone before it can be compared with LocalDateTime now_hour. So either add one to date_hours as I did in the code or remove the one from now_hour.
In my code the date_hours would get the system timezone, as the code is now. Be aware that maybe your file is not using that timezone.
Output of the example code is:
Certificates that expires:
Next week
Tomorrow
Today
Today
Cert1|
You can read more here
https://www.baeldung.com/java-8-date-time-intro
That will give you a good intro to the different date types in Java.

Java - How to get the correct date format with LocalDate

I've been having trouble correctly formatting the date as dd-MM-YYYY.
When I arrange the String dateString in the order of year-month-day, or year-day-month, it allows the date to be formatted.
It seems to only work when the yearParsed String as at the begginning of dateString.
Attempting to use DateTimeFormatter.ofPattern("dd-MM-YYYY") didn't seem to affect the date so it looks like I was not using it correctly.
Could you please let me know what I am doing wrong?
The user inputs a day, month and year one at a time, and I am looking to output the date as: 01-12-2000. The if/else are there to add a '0' in front, if the date or month input is a single digit.
Any help would be greatly appreciated.
Thank you!
String yearParsed = String.valueOf(year);
String monthParsed;
String dayParsed;
if (dayString.length() == 1) {
dayParsed = "0" + String.valueOf(day);
}
else {
dayParsed = String.valueOf(day);
}
if (monthString.length() == 1) {
monthParsed = "0" + String.valueOf(month);
}
else {
monthParsed = String.valueOf(month);
}
String dateString = yearParsed + "-" + monthParsed + "-" + dayParsed;
//String dateString = dayParsed + "-" + monthParsed + "-" + yearParsed;
System.out.println("dateString " + dateString);
LocalDate formattedDate = null;
DateTimeFormatter dateTimeFormatter;
dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
//dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-YYYY");
formattedDate = formattedDate.parse(String.format(dateString, dateTimeFormatter));
System.out.println("Formatted Date = " + formattedDate);
Regarding your variable LocalDate formattedDate, you're misunderstanding the concept of formatted date.
A formatted date is a String, because you can control it's format.
When the object is a LocalDate instance, it contains value to determine a position in the time, when you just print it it has its default formatting, it you want one specific formatting you need a String representation of your date
String year = "2021", dayString = "1", monthString = "3";
LocalDate date = LocalDate.of(
Integer.parseInt(year),
Integer.parseInt(monthString),
Integer.parseInt(dayString)
);
System.out.println(date); // 2021-03-01
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = date.format(dtf);
System.out.println("Formatted Date = " + formattedDate); // Formatted Date = 01-03-2021
You have used Y (week-based-year) instead of y (year-of-era). Learn the difference from the documentation and from answers to this question.
Simply create a LocalDate with the year, month and day and format it to a String using a DateTimeFormatter.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int day = 12, month = 6, year = 2021;
LocalDate date = LocalDate.of(year, month, day);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ENGLISH);
String formatted = dtf.format(date);
System.out.println(formatted);
}
}
Output:
2021-06-12
ONLINE DEMO
Here, you can use y instead of u but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.
Note
A LocalDate is supposed to represent date units (year, month, day), and not a specific format. The default format used by LocalDate#toString is based on ISO 8601 standard. For a specific format, you need to format it into a String as shown above. It is like representing double d = 5.0 as the 5.000 which is done by formatting d into a String of this format.
public class Main {
public static void main(String[] args) {
double d = 5.0;
NumberFormat formatter = new DecimalFormat("#0.000");
String formatted = formatter.format(d);
System.out.println(formatted);
}
}
Output:
5.000

How to limited String in Android

In my application I want to show some text (date) into TextView.
I get this Text from server and I want to show this Text in TextView.
I get this Text from server :
16 Dec 2017
But I want to show such as this :
2017
How can I remove 16 Dec ?
try this
public static String getYyyy(String date) {
String time = date;
try {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
Date date1 = format.parse(date);
if (date1 != null) {
time = new SimpleDateFormat("yyyy").format(date1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}
try this use split()
There are two signature for split() method in java string.
public String split(String regex)
and,
public String split(String regex, int limit)
use split a string in Java is to use .split(" ") which splits a string according to the pattern provided, returning a String array.
sample code
String date="16 Dec 2017";
String [] dateParts = date.split(" ");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
You can just separate the string with help of " " i.e. blank space, try to split the string with " " just like this:-
String date = "16 Dec 2017";
String[] date = date.split(" ");
//for only 2017 you can use date[2]
Be aware there are several ways more elegant and correct to do this, normally you use a Date object and just change how it looks like...
but to your wish, my answer:
I wouldnt split because is a waste to create an array for only getting one element of it...
you can use the substring method
String xdate = "16 Dec 2017";
System.out.println(xdate.substring(xdate.length() - 4, xdate.length()));
In java 8 you can do like this :
Date date = new Date(); //Create a Date object with date provided from TextBox
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Since you only want the year int year = localDate.getYear(); will give you year.
if you want substring of date in which only Year i.e. last 4 number then try below code
String date="16 Dec 2017";
int a = date.length();
String d = date.substring(a-4,a);
You can try this as well rather then split if you have date & time or more date data
String requested_date = "16 Dec 2017";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy");
Date dateObj = simpleDateFormat.parse(requested_date,new ParsePosition(0));
dateObj.getYear();

Using calendars or Joda-Time in java

I have a document that starts on date X and end on date Y and and goes up by one day. My task is to go through this document and find out how many days are missing from the document.
Example:
19990904 56.00
19990905 57.00
19990907 60.00
Need to print out that 19900906 is missing.
I have done some research and read about java calendar, Date, and Joda-Time, yet was unable to understand what any of them are. Can some one please explain what these functions I just mentioned do, and then make a suggestion on how to use one to accomplish my goal?
I already have this code:
String name = getFileName();
BufferedReader reader = new BufferedReader(new FileReader(name));
String line;
while ((line = reader.readLine()) != null)
{ //while
String delims = "[ ]+";
String [] holder = line.split(delims);
// System.out.println("*");
int date = Integer.parseInt(holder[0]);
//System.out.println(holder[0]);
double price = Double.parseDouble(holder[1]);
With JodaTime. (If you are only concerned with date, you should NOT use datetimes, or mess with hours,minutes, dst issues.)
final DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMdd");
LocalDate date=null;
while( (line = getNextLine())!=null) {
String dateAsString = line.split(delims)[0];
LocalDate founddate = dtf.parseLocalDate(dateAsString);
if(date==null) { date= founddate; continue;} // first
if(founddate.before(date)) throw new RuntimeException("date not sorted?");
if(founddate.equals(date)) continue; // dup dates are ok?
date = date.plusDays(1);
while(date.before(foundate)){
System.out.println("Date not found: " +date);
date = date.plusDays(1);
}
}
If you only need to count missing days:
LocalDate date=null;
int cont=0;
while( (line = getNextLine())!=null) {
String dateAsString = line.split(delims)[0];
LocalDate founddate = dtf.parseLocalDate(dateAsString);
if(date==null) { date= founddate; continue;} // first
if(founddate.before(date)) throw new RuntimeException("date not sorted?");
if(founddate.equals(date)) continue; // dup dates are ok?
cont += Days.daysBetween(date, founddate)-1;
date = founddate;
}
LocalDate x = new LocalDate(dateX);
LocalDate y = new LocalDate(dateY);
int i = Days.daysBetween(x, y).getDays();
missingdays = originalSizeofList - i;
This is joda-time, its much easier than vanilla java.

Java regex to extract date format out into month and year

Hi I have the following date string format:
June-2008
July-2008
March-2010
May I enquire what is the java regex to extract out whatever the month and year value into separate string each. The delimeter here is the "-" sign
Any values from the start to the end of the "-" sign is the month, anything after the "-" sign is the year value.
The following is what I would like to achieve
String m = March
String y = 2010
Thank all for your help!
Don't use a regex. Use String#split():
String[] parts = "June-2008".split("-", 2); // or .split("-")
String m = parts[0]; // "June"
String y = parts[1]; // "2008"
Even better, use SimpleDateFormat, and you'll have a proper Date to work with:
DateFormat df = new SimpleDateFormat("M-y");
Date myDate = df.parse("June-2008");
I want to extend the answer given by Matt Ball. If you want to split that string and willing to use other than String#split() you can use StringUtils of Apache Commons Lang. It has various String utility methods.
An example:
String strDate = "June-2008";
String[] parts = StringUtils.split(strDate, '-');
String month = parts[0]; // "June"
String year = parts[1]; // 2008
Also if you want to get a java.util.Date object then Joda Time may helps you. I personally prefer this api rather java.util.Date as it is far more rich, easy-to-use, less error-pron.
Now we can manipulate that String as:
String strDate = "June-2008";
DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM-yyyy");
DateTime dateTime = formatter.parseDateTime(strDate); // parse it
Date javaDate = dateTime.toDate(); // a java.util.Date object
int year = dateTime.getYear(); // 2008
String month = dateTime.month().getAsText(); // June
Hope this will help you. Thanks.

Categories