How to get day,month,year from String date? - java

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];

Related

How to parse yyyymm data format to Month, YYYY format in Java?

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

how can I change only year in date String?

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);

Convert SimpleDateFormat year to integer

I want to convert this year
SimpleDateFormat actualYear = new SimpleDateFormat("yyyy");
in an Integer variable.
Thank u!!
If you want to get int year from year string, which is in yyyy format,
int year = Integer.parseInt("2014");
If you want to get int year from current year,
int year = Calendar.getInstance().get(Calendar.YEAR);
If you want to get int year from date object,
String yearString = new SimpleDateFormat("yyyy").format(date);
int year = Integer.parseInt(yearString);
The SimpleDateFormat object just formats Date objects into strings. It is not actually aware of the date till you ask for it to format a date. The below example will print the year 2015
SimpleDateFormat format = new SimpleDateFormat("yyyy");
String formattedDate = format.format(new Date());
int year = Integer.parseInt(formattedDate);
System.out.println(year);

I want my string to converted to a day [duplicate]

This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 7 years ago.
I have this string
String s = "29/04/2015"
And I want it to produce the name of that day in my language, which is Norwegian.
For example:
29/04/2015 is "Onsdag"
30/04/2015 is "Torsdag"
How can I do this?
String dateString = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("E", Locale.no_NO);
String day = formatter.format(date);
Now day will have the day in given locale. Update
You need to configure an instance of DateFormat, with your locale, (take a look at https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html).
then parse the Date and get the day, as Dilip already suggests.
You can use date parsing combined with Locale settings to get the desired output. For e.g. refer following code.
String dateStr = "29/04/2015";
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date dt = dtf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
String m = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG_FORMAT, new Locale("no", "NO"));
System.out.println(m);
For more information about locale, visit Oracle Java Documentation.
First you will need to parse the String to a Date. Then use a Calendar to get the day of the week. You can use an array to convert it to the appropriate string.
// Array of Days
final String[] DAYS = {
"søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"
};
// Parse the date
final String source = "27/04/2015";
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = format.parse(source);
} catch (final ParseException e) {
e.printStackTrace();
}
// Convert to calendar
final Calendar c = Calendar.getInstance();
c.setTime(date);
final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
// Get the day's name
System.out.println("Day of Week: " + dayOfWeek);
System.out.println("Day = " + DAYS[dayOfWeek - 1]);
You need to parse your text with date to Date instance and then format it back to text. You can do it with SimpleDateFormat class which supports many patterns of dates like
dd/MM/yyyy for your original date,
and EEEE for full name of day in month.
While formatting you will also need to specify locale you want to use. To create Norway specific locale you can use for instance
Locale nor = Locale.forLanguageTag("no-NO");
So your code can look more or less like:
String text = "29/04/2015";
Locale nor = Locale.forLanguageTag("no-NO");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", nor);
SimpleDateFormat dayOfWeek = new SimpleDateFormat("EEEE", nor);
Date date = sdf.parse(text);
System.out.println(dayOfWeek.format(date));
Output: onsdag.
final int SUNDAY = 1;
final int ONSDAG = 2;
final int TORSDAG = 3;
....
....
String s = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day) {
case(ONSDAG):
dayString = "ONSDAG";
break;
....
}
EDIT: I just tested this and it actually starts from Sunday, and returns the value of 1 for sunday, I've changed the constant values to reflect this.
First you'll need a Calendar object.
Calendar cal = Calendar.getInstance();
String s = "29/04/2015"
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
cal.setTime(format.parse(s));
From the Calendar you can get the day of the week.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
dayOfWeek will be 1-7 with Sunday (in english) being 1
You can use an HashMap map where the first parametri is the date "29/4/2015" while the second is the meaning. You can use your string to get the meaning map.get (yourString).

Convert Data format using SimpleDateFormat

I need to convert date format into NEW_FORMAT date format. I want to show like this June 28,2016 ,but its showing January irrespective of any month number I pass. Please check where I am missing..
public class DateClass {
public static void main(String[] args)
{
final String OLD_FORMAT = "yyyy-mm-dd";
final String NEW_FORMAT = "MMMM dd,yyyy";
String oldDateString = "2016-06-28";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d;
try {
d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
System.out.println(""+newDateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
your OLD_FORMAT is wrong, it should be "yyyy-MM-dd". Here small m should be replaced by capital M, since small m represents minutes and M represents month of year, and while parsing using OLD_FORMAT, date is getting parsed wrongly.
You're using mm in OLD_FORMAT which stands for minute. You want to have MM which stands for month.
Therefore your OLD_FORMAT should be yyyy-MM-dd.
The minute is set to 0 in your case therefore the month is January.
change this one
final String OLD_FORMAT = "yyyy-mm-dd";
to
final String OLD_FORMAT = "yyyy-MM-dd";
In java, mm represents as minuets and MM represents as Month, so you have to change your code as
final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "MMMM dd,yyyy";
String oldDateString = "2016-06-28";

Categories

Resources