I have java date string.
How can I change its year without changing the month and date.
e.g.
parts1[1]= 2020-1-2;
parts1[2]= 13:48:21;
CreatedDate = parts1[1]+" "+parts1[2];
System.out.println(CreatedDate);
I want to change it to
parts1[1]= 2021-1-2;
parts1[2]= 13:48:21;
CreatedDate = parts1[1]+" "+parts1[2];
System.out.println(CreatedDate);
I basically want to change the year without changing month and date
Can it be done?
java.time
You do not have to split the string and then combine the parts. You can parse the whole string into LocalDateTime and then use LocalDateTime#withYear to get a new instance with the specified year.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String creationDateTime = "2020-1-2 13:48:21";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-M-d H:m:s", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(creationDateTime, dtf);
System.out.println(ldt);
ldt = ldt.withYear(2021);
// Default format
String updatedDateTime = ldt.toString();
System.out.println(updatedDateTime);
// Custom format
updatedDateTime = ldt.format(dtf);
System.out.println(updatedDateTime);
}
}
Output:
2020-01-02T13:48:21
2021-01-02T13:48:21
2021-1-2 13:48:21
Learn more about java.time API from Trail: Date Time.
try:
String[] arrOfStr = parts1[1].split("-", 2);
arrOfStr[0] contains the year
Now you need to parse it as an int (since it's only 4 digits)
int year = Integer.parseInt(arrOfStr[0]);
year now contains the the number 2020.
you can do
year++;
to increase it's value by 1
and to put it back in String format do:
arrOfStr[0] = "" + year;
or
arrOfStr[0] = String.valueOf(year);
to put it all together do this
parts1[1]= arrOfStr[0] + "-" arrOfStr[1]; // 2021-1-2
finally it should look like this:
parts1[1]= 2020-1-2;
parts1[2]= 13:48:21;
String[] arrOfStr = parts1[1].split("-", 2);
int year = Integer.parseInt(arrOfStr[0]);
year++;
arrOfStr[0] = "" + year;
parts1[1]= arrOfStr[0] + "-" + arrOfStr[1];
CreatedDate = parts1[1]+" "+parts1[2];
System.out.println(CreatedDate);
Related
I have a string value which is equal to "202004". how can I convert it to "April, 2020" in Java?
I would use java.time for a task like this.
You can define two java.time.format.DateTimeFormatter instances (one for parsing the input string to java.time.YearMonth and another for formatting the obtained YearMonth to a string of the desired format).
Define a method like this one:
public static String convert(String monthInSomeYear, Locale locale) {
// create something that is able to parse such input
DateTimeFormatter inputParser = DateTimeFormatter.ofPattern("uuuuMM");
// then use that formatter in order to create an object of year and month
YearMonth yearMonth = YearMonth.parse(monthInSomeYear, inputParser);
/*
* the output format is different, so create another formatter
* with a different pattern. Please note that you need a Locale
* in order to define the language used for month names in the output.
*/
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(
"MMMM, uuuu",
Locale.ENGLISH
);
// then return the desired format
return yearMonth.format(outputFormatter);
}
then use it, e.g. in a main method:
public static void main(String[] args) {
// your example input
String monthInAYear = "202004";
// use the method
String sameMonthInAYear = convert(monthInAYear, Locale.ENGLISH);
// and print the result
System.out.println(sameMonthInAYear);
}
The output will be this:
April, 2020
Use below one line code to format year month
int yearMonth = Integer.parseInt("202004");
String yearMonthStr = new DateFormatSymbols().getMonths()[(yearMonth % 10)-1] + ", "+yearMonth/100;
System.out.println(yearMonthStr);
Use DateFormatSymbols() class to implement the new date format from the string
String text="202011";
int num=0;
//Checking the last second character of the text for jan to sept month
if(text.charAt(text.length()-2)==0){
num=Integer.parseInt(""+text.charAt(text.length()-1))-1;
}
else {
num=Integer.parseInt(""+text.substring(text.length()-2))-1;
}
//Checking correct month value
if(num>=0&&num<=11){
String month = "";
DateFormatSymbols date_ = new DateFormatSymbols();
String[] month_name = date_.getMonths();
month = month_name[num];
System.out.println(month+","+text.substring(0,4));
}
else{
System.out.println("Wrong month value");
}
SimpleDateFormat oldFormat = new SimpleDateFormat("yyyyMM");
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM, yyyy");
Date date = null;
try {
date = oldFormat.parse("202004");
} catch (ParseException e) {
e.printStackTrace();
}
String newDateString = newFormat.format(date);
SimpleDateFormat documentation
Let try my code snippet:
SimpleDateFormat inSdf = new SimpleDateFormat("yyyyMM");
Date date = inSdf.parse("202112");
SimpleDateFormat outSdf = new SimpleDateFormat("MMMM, yyyy");
String sDate = outSdf.format(date);
System.out.println(sDate);
Result:
December, 2021
I have a beginning date, let us say it is 2020-12-30 08:00:00, and I have an end date, let us say it is 2021-02-11 16:00:00.
I need to get the hours between these days which I do by using:
long diffInHours = TimeUnit.HOURS.convert(Math.abs(closeStoreDateTime.getTime() - openStoreDateTime.getTime()), TimeUnit.MILLISECONDS);
My issue is that as I iterate downward from the end date to the beginning date, I am converting the hour difference between the current hour and the beginning hour into an accurate time to store in a map later on. Like this:
int latestHour = (int) diffInHours;
while (latestHour >= openStoreDateTime.toInstant().atZone(ZoneId.systemDefault()).getHour()) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.systemDefault()));
String hourConversion;
if (closeStoreDateTime.toInstant().atZone(ZoneId.systemDefault()).getDayOfYear() > openStoreDateTime.toInstant().atZone(ZoneId.systemDefault()).getDayOfYear()) {
if (latestHour > 24) {
calendar.add(Calendar.HOUR_OF_DAY, latestHour);
hourConversion = calendar.get(Calendar.AM_PM) == Calendar.AM ? String.valueOf(calendar.get(Calendar.HOUR)) : String.valueOf(calendar.get(Calendar.HOUR) + 12);
} else {
calendar.add(Calendar.HOUR_OF_DAY, latestHour);
int AM_PM = calendar.get(Calendar.AM_PM);
if (AM_PM == Calendar.AM || (AM_PM == Calendar.PM && calendar.get(Calendar.HOUR) == 12)) {
hourConversion = String.valueOf(calendar.get(Calendar.HOUR));
} else {
hourConversion = String.valueOf(calendar.get(Calendar.HOUR) + 12);
}
}
} else {
hourConversion = String.valueOf(latestHour);
}
This works if the dates are within the same year, but does not work if they are in different years because the day in the begin year (363) is greater than the day in the end year. Does anyone have an idea how to convert hours between 2 different dates into a useable date? Thank you.
If I understand your question correctly, you want a List of date-time values from an end date-time through a start date-time, one for each hour.
Here are some test results.
2021-02-11T16:00
2021-02-11T15:00
2021-02-11T14:00
2021-02-11T13:00
2021-02-11T12:00
...
2020-12-30T12:00
2020-12-30T11:00
2020-12-30T10:00
2020-12-30T09:00
2020-12-30T08:00
Here's runnable code that will do that using the LocalDateTime class. You can display a LocalDateTime value anyway you want using a DateTimeFormatter.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class DateIntervals {
public static void main(String[] args) {
String endDateString = "2021-02-11 16:00:00";
String startDateString = "2020-12-30 08:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd HH:mm:ss");
LocalDateTime endDate = LocalDateTime.parse(endDateString, formatter);
LocalDateTime startDate = LocalDateTime.parse(startDateString, formatter);
List<LocalDateTime> intervals = new ArrayList<>();
LocalDateTime date = endDate;
while (date.isAfter(startDate)) {
intervals.add(date);
date = date.minusHours(1L);
}
intervals.add(date);
for (int i = 0; i < intervals.size(); i++) {
System.out.println(intervals.get(i));
}
}
}
I just need to change month number to a month name...
I tried to put three M's instead of two, and it shows error.
I kinda know the problem but don't know how to fix it.
DateTimeFormatter formater = DateTimeFormatter.ofPattern("ddMMyyyy");
Person[] people = new Person[parts.length / 4];
int br = 0;
for (int i = 0; i < parts.length; i += 4) {
LocalDate datum = LocalDate.parse(parts[i + 2], formater);
people[br++] = new Person(parts[i], parts[i + 1],datum, parts[i + 3]);
}
Instead of "1988-05-05",
this "1988-May-05" ...
Following can be used for formatting the way you want:
DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now()) //2019-02-04
DateTimeFormatter.ofPattern("yyyy-MMM-dd").format(LocalDate.now()) //2019-Feb-04
DateTimeFormatter.ofPattern("yyyy-MMMM-dd").format(LocalDate.now()) //2019-February-04
It looks like you've already parsed your date. To convert a LocalDate to the kind of string you'd like, you can use the following formatter:
LocalDate date = LocalDate.of(2018, 1, 1);
DateTimeFormatter out = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendLiteral('-')
.appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT)
.appendLiteral('-')
.appendValue(ChronoField.DAY_OF_MONTH, 2)
.toFormatter(Locale.UK); // or your locale
System.out.println(
out.format(date)
);
First you parse a String representation of a Date like this:
DateTimeFormatter formater = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate datum = LocalDate.parse("04022019", formater);
Now if the parsing succeeded and you have a valid LocalDate object,
you can format it:
String date = datum.format(DateTimeFormatter.ofPattern("yyyy-MMM-dd"));
System.out.println(date);
will print
2019-Feb-04
Try:
int month=5;
String name = java.time.Month.values()[month-1].name();
It has also a getDisplayName method:
String name = java.time.Month.values()[month-1].getDisplayName(TextStyle.FULL, Locale.getDefault());
or(from commment)
String name =java.time.Month.of(month).getDisplayName(TextStyle.FULL, Locale.getDefault());`
(or something alike)
The LocalDate class also provides several getter methods to extract these values as shown below:
LocalDate currentDate = LocalDate.of(2019, 02, 04);
(OR)
LocalDate currentDate = LocalDate.now(); // 2019-02-04
DayOfWeek dayOfWeek = currentDate.getDayOfWeek(); // TUESDAY
int dom = currentDate.getDayOfMonth(); // 04
int doy = currentDate.getDayOfYear(); // 35
Month month = currentDate.getMonth(); // FEBRUARY
int year = currentDate.getYear(); // 2019
I have a date on String, like this:
String date="25.07.2007";
And I want to divide it to:
String day;
String month;
String year;
What is the best way to do this?
One way to split a string in Java is to use .split("regex") which splits a string according to the pattern provided, returning a String array.
String [] dateParts = date.split(".");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
To get current date:
You can also change the format of the date by changing the values passed to SimpleDateFormat. Don't forget the imports.
DateFormat dateFormater = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date date = new Date();
java.time
The modern way is to use the Android version of the back-port of the java.time framework built into Java 8 and later.
First, parse the input string into a date-time object. The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "25.07.2007";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM.dd.yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Now you can ask the LocalDate for its values.
int year = localDate.getYear();
int month = localDate.getMonthValue();
int dayOfMonth = localDate.getDayOfMonth();
You can use the handy Month enum to localize the name of the month.
String monthName = localDate.getMonth().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
Try this...
String dateArr[] = date.split(".");
String day = dateArr[0];
String month = dateArr[1];
String year = dateArr[2];
or
String day = date.substring(0,2);
String month = date.substring(3,5);
String year = date.substring(6,10);
To get the current date...
Date currentDate = Calendar.getInstance().getTime();
To get day, month and year from current date..
int day = currentDate.get(Calendar.DAY_OF_MONTH);
int month = currentDate.get(Calendar.MONTH);
int year = currentDate.get(Calendar.YEAR);
Month starts at 0 here...
public class DateTest {
/**
* #param args
* #throws ParseException
*/
public static void main(String[] args) throws ParseException {
String starDate = "7/12/1995 12:00:00 AM";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
String newDateStr = simpleDateFormat.format(simpleDateFormat.parse(starDate));
String str[] = newDateStr.split("/");
String month = str[1];
String year = str[2];
}
}
Note: date.split(".") will not work. Split methods takes regex as parameter. For regex "." means any character. Instead we have to pass "\\." as parameter.
String [] dateParts = date.split("\\.");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
I have been trying to use the date.format(DateTimeFormatter formatter) method to format a list of date strings, where 'date' is a java.time.LocalDate object, for example. The problem is, I cannot find a straight-forward way to create a Year object from a string. For instance, if I have the string yearString = "90". I would like to create a Year object that is equal to this value, and then use the format method to output yearStringNew = "1990". The closest I see to a public constructor is the now() function which returns the current time.
I have also looked into creating a Calendar object and then creating a format-able date object there, but I can only create a Java.util.Date object – as opposed to an object in the Java.time package which could then ideally be formatted by the format function. Am I missing something here?
FYI I'm referencing the Java 8 SDK javadoc https://docs.oracle.com/javase/8/docs/api/
Thank you for your time.
EDIT: Per the request of another user, I have posted my code below; this is the closest I have come to accomplishing what I'm looking for:
//Module 3:
//Format Date Segments
package challenge245E;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class TestClass3 {
public static void main(String[] args) throws ParseException {
DateFormatter dateFormatter = new DateFormatter();
String myGroupedSlices [][] =
{
{"1990", "12", "06"},
{"12","6", "90"}
};
dateFormatter.formatDates(myGroupedSlices);
}
}
class DateFormatter {
public Date[][] formatDates(String[][] groupedDates) throws ParseException {
Date[][] formattedDates = new Date[groupedDates.length][3];
DateFormat yearFormat = new SimpleDateFormat("YYYY");
DateFormat monthFormat = new SimpleDateFormat("MM");
DateFormat dayFormat = new SimpleDateFormat("dd");
//iterate through each groupedSlices array
for (int i=0; i<groupedDates.length;i++) {
//Conditions
if (groupedDates[i][0].length()<3) {
//MDDYY format: if date[0].length < 3
//Re-arrange into YDM order
String m = groupedDates[i][0];
String y = groupedDates[i][2];
groupedDates[i][0] = y;
groupedDates[i][2] = m;
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("MDY Order: " + Arrays.toString(formattedDates[i]));
}
if (groupedDates[i][0].length()>3) {
//YYYYMMDD format: if date[0].length > 3
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("YMD Order: " + Arrays.toString(formattedDates[i]));
}
}
return formattedDates;
}
}
If I understand your requirement correctly, have a look at the LocalDate.parse() methods.
Example:
LocalDate date = LocalDate.parse("1990-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
int year = date.getYear(); // 1990
Parse Each Number Separately
It’s good to see you using the java.time framework rather than the troublesome old date-time classes. The old java.util.Date/.Calendar classes have been supplanted by the new framework.
The DateTimeFormatter class parses any two digit year as being in the 2000s. From class doc:
If the count of letters is two… will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
To override this behavior, see this Answer by assylias. But that issue may be moot in your case. You already have the individual year, month, and date values isolated. So they need not be parsed together.
I suggest you convert each string into a integer. For the year, if less than 100 then add 1900.
String inputYear = "90";
String inputMonth = "12";
String inputDayOfMonth = "6";
int year = Integer.parseInt( inputYear );
int month = Integer.parseInt( inputMonth );
int dayOfMonth = Integer.parseInt( inputDayOfMonth );
if( year < 100 ) { // If two-digit year, assume the 1900s century. Even better: Never generate two-digit year text!
year = ( year + 1900 );
}
LocalDate localDate = LocalDate.of( year , month , dayOfMonth );
Create an Instance of class GregorianCalendar, set your date in that calendar and then use the method toZonedDateTime(). This will give you ZonedDateTime instance. form it you can use method LocalDate.from(TemporalAccessor temporal) method to get your LocalDate. Here how it might look:
//....
GregorianCalendar calendar = new GregorianCalendar();
// Set the deasired date in your calendar
LocalDate localDate = LocalDate.from(calendar.toZonedDateTime());
//...
import java.time.LocalDate;
public class DaysTilNextMonth {
public static void main(String[] args) {
//create an object for LocalDate class
LocalDate date = LocalDate.now();
//get today's day
int today = date.getDayOfMonth();
//get number of days in the current month
int numOfDaysInMonth = date.lengthOfMonth();
//compute the days left for next month
int dayForNextMonth = numOfDaysInMonth - today;
//display the result
System.out.println("The next month is: " + date.plusMonths(7).getMonth());
System.out.println("We have " + dayForNextMonth + " days left until first day of next month.");
}
}