how to break a string into two parts in java - java

Let's assume a string consists of two parts, day and date.
String arr[] = { "Tuesday 8/11/22", "Monday 15/3/21", "Friday 20/5/21" };
How can I only print out the latter part (date part) on console?

I recommend you use the date-time API instead of performing string manipulation of the elements. The string manipulation will not give you all the benefits that you can get by the specialized date-time API.
Bonus
You get your dates validated free of cost e.g. one of your dates, Friday 20/5/21 is incorrect. This date was Thursday and the java.time API can perform this check for you automatically.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String arr[] = { "Tuesday 8/11/22", "Monday 15/3/21", "Friday 20/5/21" };
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEEE d/M/uu", Locale.ENGLISH);
for (String s : arr) {
LocalDate date = LocalDate.parse(s, parser);
// Now you can get individual units from date in a variety of ways
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH));
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
System.out.println(date.getYear());
// You can also format it in the desired ways
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/uu", Locale.ENGLISH);
String formatted = date.format(formatter);
System.out.println(formatted);
}
}
}
Output:
Tuesday
Tue
2022
8/11/22
Monday
Mon
2021
15/3/21
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Friday 20/5/21' could not be parsed: Conflict found: Field DayOfWeek 4 differs from DayOfWeek 5 derived from 2021-05-20
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2023)
Learn more about the modern Date-Time API from Trail: Date Time.

As long as the day and date will stay in that format you can use the split() function:
class DateSplit {
public static void main(String[] args) {
String a = "Tuesday 8/11/22";
String[] result = a.split(" ");
System.out.println(result[1]);
}
}
where the delimiter splitting the string is the whitespace character.

for(String str : arr) {
System.out.println(str.split(" ")[1])
}

public class Main {
public static void main(String[] args) {
String arr[] = { "Tuesday 8/11/22", "Monday 15/3/21", "Friday 20/5/21" };
for(int count = 0; count < arr.length; count++) {
String[] s = arr[count].split(" ");
System.out.println(s[1]);
}
}
}

Related

Can we remove unwanted delimiters from java

I wanted that the program takes input removes the delimiters from that String then add it back then I can later parse it to a LocalDate object but I am not able to do the needful.
Scanner darshit = new Scanner(System.in);
String oo = "";
System.out.println("Enter your DOB: ");
String dob = darshit.next();
String[] words = dob.split("\\D");
for (int i = 0; i > words.length; i++) {
oo = oo + words[i];
}
System.out.println(oo);
After entering the DOB as 25-06-2008, for example, the output should be 25062008 or 2662008 but instead of this, I get a blank line!
Use DateTimeFormatter to parse the input string to LocalDate and then format the LocalDate into a String of the desired format.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner darshit = new Scanner(System.in);
System.out.print("Enter your DOB: ");
String dob = darshit.next();
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("dd[-][/]MM[-][/]uuuu", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dob, dtfInput);
// Output in the default format i.e. LocalDate#toString implementation
// System.out.println(date);
// Output in a custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("ddMMuuuu", Locale.ENGLISH);
String formatted = dtfOutput.format(date);
System.out.println(formatted);
}
}
Notice the optional patterns in the square bracket which one of the great things about DateTimeFormatter.
A sample run:
Enter your DOB: 25-06-2008
25062008
Another sample run:
Enter your DOB: 25/06/2008
25062008
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.
Can you just use Java Streams with the Collectors joining call ?
String value = Arrays.asList(dob.split("\\D")).stream().collect(Collectors.joining());
String.replaceAll() and DateTimeFormatter
private static final DateTimeFormatter DATE_PARSER
= DateTimeFormatter.ofPattern("[-]d-M-u[-]", Locale.ROOT);
private static final DateTimeFormatter DATE_FORMATTER
= DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ROOT);
public static void parseAndFormat(String input) {
String adapted = input.replaceAll("\\W+", "-");
System.out.println("Adapted input string: " + adapted);
LocalDate date = LocalDate.parse(adapted, DATE_PARSER);
String formatted = date.format(DATE_FORMATTER);
System.out.println("Formatted: " + formatted);
}
The above method parses your string:
parseAndFormat("25-06-2008");
Output:
Adapted input string: 25-06-2008
Formatted: 25-06-2008
It’s very tolerant to which delimiters the users decides to use between the numbers, and also before or after them if any:
parseAndFormat("$5///7 2008 ?");
Adapted input string: -5-7-2008-
Formatted: 05-07-2008
How it works: input.replaceAll("\\W+", "-") substitutes any run of non-word characters — everything but letters a through z and digits 0 through 9 — with a single hyphen. No one is interested in seeing the adapted input string, I am only printing it for you to understand the process better. The formatter I use for parsing accepts an optional hyphen first and last. The square brackets in the format pattern denote optional parts. It also accepts day and month in 1 or 2 digits and year in up to 9 digits. I use a separate formatter for formatting so I can control that day and month come in 2 digits and there are no hyphens before nor after.
I myself found the solution
import java.util.Scanner;
import java.time.format.*;
import java.time.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your DOB: ");
String dateOfBirth = scanner.next();
String dateOfBirth1 = dateOfBirth.replaceAll("\\s", "");
String[] dateOfBirthArray = dateOfBirth1.split("[\\s\\-\\.\\'\\?\\,\\_\\#]+");
int[] dateOfBirthArray1 = new int[dateOfBirthArray.length];
for (int i = 0; i < dateOfBirthArray.length; i++){
dateOfBirthArray1[i] = Integer.parseInt(dateOfBirthArray[i]);
}
int dayDateOfBirth = dateOfBirthArray1[0] , monthDateOfBirth = dateOfBirthArray1[1];
int yearDateOfBirth = dateOfBirthArray1[2];
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(yearDateOfBirth, monthDateOfBirth, dayDateOfBirth);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String birthday1 = birthday.format(formatter);
}
}
According to me it is the easiest way and the public editors can edit the post for making it more clear

How do I convert String.split to int

String nDate;
String dateTemp;
int i;
nDate = kb.nextLine();
String[] temp = nDate.split("-");
int numDate = Integer.parseInt(String.valueOf(temp));
im having issues with the (temp) part in the last line. If for example my input is "06-21-2020", what I want to happen is it becomes "06212020"
Use replace() instead of split(). To further explain, String.valueOf() does not take an array of Strings.
String temp = nDate.replace("-","");
int numDate Integer.parseInt(temp);
java.time
The answer by Phaelax z is spot-on for your specific requirement.
However, I recommend you parse the date string to LocalDate and format it as you wish.
You will get much more than the required conversion e.g. just think of finding the name of the day on 06-21-2020 or something like converting to some other format e.g. Sun 21 June 2020. All such requirements can be easily done using the in-built API as shown in the following demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String nDate = "06-21-2020";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.ENGLISH);
LocalDate date = LocalDate.parse(nDate, dtfInput);
DateTimeFormatter dtfOutput1 = DateTimeFormatter.ofPattern("MMdduuuu", Locale.ENGLISH);
DateTimeFormatter dtfOutput2 = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
DateTimeFormatter dtfOutput3 = DateTimeFormatter.ofPattern("EEE dd MMM uuuu", Locale.ENGLISH);
System.out.println(dtfOutput1.format(date));
System.out.println(dtfOutput2.format(date));
System.out.println(dtfOutput3.format(date));
}
}
Output:
06212020
21/06/2020
Sun 21 Jun 2020
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.

How to required Date and time using Java?

**I am trying to write the code for getting the date in required format , I have got the dates but how to add the required time with it ,
here I have
startDate - 1/08/2021 00:00:00 ,
EndDate - 20/08/2021 23:59:59 ,
increment days: 10
and the Expected output is :
05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,
This is the Code which I was trying to write , any help is appreciated
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DateTest {
public static List<LocalDate> getDaysBetweenDates(LocalDate startDate, LocalDate endDate, int interval) {
List<LocalDate> dates = new ArrayList<>();
while (endDate.isAfter(startDate)) {
dates.add(startDate);
startDate = startDate.plusDays(interval-1);
dates.add(startDate);
startDate = startDate.plusDays(1);
}
return dates;
}
public static void main(String[] args) {
int interval = 5;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss",Locale.US);
List<LocalDate> daysBetweenDates = getDaysBetweenDates(LocalDate.parse("01-08-2021 00:00:00", formatter),
LocalDate.parse("20-08-2021 23:59:59", formatter), interval);
System.out.println(daysBetweenDates);
}
}
Here's an alternative that uses LocalDates only (OK, and LocalDateTimes internally):
public static void printDaysInPeriod(LocalDate start, LocalDate end, int interval) {
// provide some data structure that
Map<LocalDate, LocalDate> intervals = new TreeMap<LocalDate, LocalDate>();
// loop through the dates in the defined period
while (start.isBefore(end)) {
// use the interval as step
LocalDate intervalEnd = start.plusDays(interval);
// store the sub-interval in the data structure
intervals.put(start, intervalEnd);
// and rearrange "start" to be the day after the last sub-interval
start = intervalEnd.plusDays(1);
}
// provide a formatter that produces the desired output per datetime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"dd/MM/uuuu HH:mm:ss"
);
// provide a data structure for the output parts (Strings here)
List<String> intervalOutput = new ArrayList<>();
// stream the sub-intervals
intervals.entrySet().forEach(e ->
// then produce the desired output per sub-interval and store it
intervalOutput.add(e.getKey().atStartOfDay()
.format(formatter)
+ " to "
+ e.getValue()
.atTime(LocalTime.MAX)
.format(formatter)));
// finally output the sub-interval Strings comma-separated
System.out.println(String.join(" , ", intervalOutput));
}
Using this method in a main, like this
public static void main(String[] args) {
// example dates defining an interval
String startInterval = "05/08/2021";
String endInterval = "15/08/2021";
// provide a parser that handles the format
DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// then parse the dates to LocalDates
LocalDate start = LocalDate.parse(startInterval, dateParser);
LocalDate end = LocalDate.parse(endInterval, dateParser);
// and use the method
printDaysInPeriod(start, end, 5);
}
produces the following output:
05/08/2021 00:00:00 to 10/08/2021 23:59:59 , 11/08/2021 00:00:00 to 16/08/2021 23:59:59
You changed your questions a few times and in the first reading, I thought that you have start and end Date-Times as String. Based on this understanding, I wrote this answer. However, the very next minute, deHaar posted this correct answer. I am leaving this answer here for someone who will be looking for a solution to this kind of requirement (i.e. with Date-Time as String).
You can do it in the following two simple steps:
Define separate DateTimeFormatter for the input and the output strings
Loop through the parse range of Date-Time.
Demo
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strStartDateTime = "1/08/2021 00:00:00";
String strEndDateTime = "20/08/2021 23:59:59";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u H:m:s", Locale.ENGLISH);
LocalDateTime startDateTime = LocalDateTime.parse(strStartDateTime, dtfInput);
LocalDateTime endDateTime = LocalDateTime.parse(strEndDateTime, dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
for (LocalDateTime ldt = startDateTime, nextDateTime = ldt.plusDays(10).minusSeconds(1); !ldt
.isAfter(endDateTime); ldt = ldt.plusDays(10), nextDateTime = ldt.plusDays(10).minusSeconds(1))
System.out.println(dtfOutput.format(ldt) + " - " + nextDateTime);
}
}
Output:
2021-08-01 00:00:00 - 2021-08-10T23:59:59
2021-08-11 00:00:00 - 2021-08-20T23:59:59
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.
Use the date-time API.
(The code should be self-explanatory.)
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class DateTest {
public static List<ZonedDateTime> getDaysBetweenDates(ZonedDateTime startDate, ZonedDateTime endDate, int interval) {
List<ZonedDateTime> dates = new ArrayList<>();
while (!startDate.isAfter(endDate)) {
dates.add(startDate);
if (Period.between(startDate.toLocalDate(), endDate.toLocalDate()).getDays() < interval) {
startDate = endDate;
}
else {
startDate = startDate.plusDays(interval);
}
dates.add(startDate);
startDate = startDate.plusDays(1);
}
return dates;
}
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
List<ZonedDateTime> dates = getDaysBetweenDates(ZonedDateTime.of(LocalDateTime.parse("05/08/2021 00:00:00", formatter), ZoneId.systemDefault()),
ZonedDateTime.of(LocalDateTime.parse("15/08/2021 23:59:59", formatter), ZoneId.systemDefault()),
5);
for (int i = 0; i < dates.size(); i+=2) {
System.out.printf("%s to %s , ",
dates.get(i).format(formatter),
dates.get(i + 1).format(formatter));
}
}
}
Output when running above code as follows:
05/08/2021 00:00:00 to 10/08/2021 00:00:00 , 11/08/2021 00:00:00 to 15/08/2021 23:59:59 ,

Java LocalDate How to utilize

input list
from date ex) 2020-10-01
to date ex) 2020-10-30
List [day of week] ex) [sun,mon....]
List [week] ex) [1,4,5]
I would like to know how to get a specific day of the week between the two dates.
Thank.
from date ex) 2020-10-01 to date ex) 2020-10-30
Your input string is already in the ISO8601 format for date and therefore it can be parsed without providing a DateTimeFormatter explicitly. In order to get the output string in a custom format (e.g. yyyy-MM-dd), you need to format the date object using DateTimeFormatter.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String inputStrDate = "2020-10-01";
LocalDate date = LocalDate.parse(inputStrDate);
String outputStrDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(outputStrDate);
}
}
Output:
2020-10-01
However, if your input is some other format, you will need to use DateTimeFormatter in order to parse it to a date object.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Formatter for input string
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String inputStrDate = "10-01-2020";
LocalDate date = LocalDate.parse(inputStrDate, inputFormat);
// Formatter for output string
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String outputStrDate = date.format(outputFormat);
System.out.println(outputStrDate);
}
}
Output:
2020-10-01
Learn more about date-time API from Trail: Date Time.
for(LocalDate d = fromDate; !d.isAfter(toDate); d = d.plusDays(1)) { // 일정 시작 ~ 끝 loop
for (Integer wf : weekOfMonth) {
for (Integer df : dayOfWeek) {
offDay = d.with(fieldWeek, wf)
.with(fieldDay, df);
if (d.getMonth() == offDay.getMonth() && !offDays.contains(offDay)) {
offDays.add(offDay);
}
}
}
}
Sorry for asking the wrong question.
And thank you very much.
I've already made it, but I've studied your code.
java.time
I too recommend that you use java.time, the modern Java date and time API, for your date work. My shot is:
LocalDate fromDate = LocalDate.of(2020, Month.OCTOBER, 1);
LocalDate toDate = LocalDate.of(2020, Month.OCTOBER, 30);
List<DayOfWeek> daysOfWeek = List.of(DayOfWeek.SUNDAY, DayOfWeek.MONDAY);
List<Integer> weeks = List.of(1, 4, 5);
if (! YearMonth.from(fromDate).equals(YearMonth.from(toDate))) {
throw new IllegalStateException("Covering more than one month is not yet supported");
}
WeekFields wf = WeekFields.SUNDAY_START;
for (int week : weeks) {
for (DayOfWeek dow : daysOfWeek) {
LocalDate date = fromDate.with(wf.weekOfMonth(), week)
.with(wf.dayOfWeek(), dow.get(wf.dayOfWeek()));
// Is date inside interval?
if (! (date.isBefore(fromDate) || date.isAfter(toDate))) {
System.out.println(date);
}
}
}
Output:
2020-10-18
2020-10-19
2020-10-25
2020-10-26
The dates printed are Sunday and Monday of weeks 4 and 5 of October defining weeks in the American way where the week begins on Sunday (since you mentioned Sunday first in your example list) and week 1 is the week of October 1. Sunday and Monday of week 1 are not printed because they fall before October 1, that is, in September.
Consider which week scheme you require. You may use for example WeekFields.ISO or WeekFields.of(Locale.getDefault()).
I am finding the week first, then the day of week, because to me this is the natural way. I need to use the WeekFields object for both adjustments to make sure that the chosen week scheme is respected.
If you need to cover more than one calendar month, iterate over the months and do the same for each. Also check that the result date falls within the month so duplicates near month borders are ignored.

convert date into different format

I am trying to convert date into user required format. I want date in all format.
But formatted date is wrong please help.
package DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormat
{
DateFormat() throws ParseException
{
String dateFormats[] =
{
"YYYY/MM/DD",
"DD/MM/YYYY",
"DD-MM-YYYY",
};
for (int i = 0; i < dateFormats.length; i++)
{
String newDate = new SimpleDateFormat(dateFormats[i]).format(new Date());
System.out.println(newDate);
}
}
public static void main(String[] args) throws ParseException
{
new DateFormat();
}
}
output is
2016/04/98
98/04/2016
98-04-2016
Thank you.
It's going wrong because of java code syntax case sensitive.
Pls check the right date and time pattern at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your String array of patterns should be transformed to:
String dateFormats[] =
{
"yyyy/MM/dd",
"dd/MM/yyyy",
"dd-MM-yyyy",
};
D Day in year Number 189
d Day in month Number 10
from https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
So, formats should look like:
String dateFormats[] =
{
"yyyy/MM/dd",
"dd/MM/yyyy",
"dd-MM-yyyy",
};

Categories

Resources