Time from month number to a month name? - java

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

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

Parse seconds-of-day as part of a date string

I need to parse a date string which has the following format:
yyyy-MM-dd TTTTT. All pattern letters are the standard DateTimeFormatter letters, except for the TTTTT part, which is a seconds-of-day field.
As there is no pattern defined for such a field, I needed to come up with something else. My first thought was to try and parse the field as milli-of-day (A), but by using 5 A's my field is treated as the least significant characters which is... yeah, not what I want.
Is there any out-of-the box solution I could use or do I have to resort to some custom made solution (like ignoring the TTTTT field, parsing it manually and using LocalDateTime.plusSeconds() on the resulting date)?
In other words, how can I make the following test case pass?
public class DateTimeParserTest {
private static final String PATTERN = "yyyy-MM-dd TTTTT";
private static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern(PATTERN);
#Test
public void testParseSecondsOfDay() throws Exception {
String input = "2016-01-01 86399";
LocalDateTime localDateTime = LocalDateTime.parse(input, FORMATTER);
assertEquals("2016-01-01T23:59:59", localDateTime.toString());
}
}
Based on your correction (leaving out the potentially ambivalent part "HH:mm") the Java-8-solution would look like:
private static final DateTimeFormatter FORMATTER =
new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd ")
.appendValue(ChronoField.SECOND_OF_DAY, 5)
.toFormatter();
well it may not be what what you are looking, but i hope it helps
private static final String PATTERN = "yyyy-MM-dd HH:mm:ss"; //MODIFICATION HERE
private static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern(PATTERN);
#Test
public void testParseSecondsOfDay() throws Exception {
String input = "2016-01-01 00:00:86399";
int lastIndexOf = input.lastIndexOf(':');
CharSequence parsable = input.subSequence(0,lastIndexOf)+":00";
CharSequence TTTTPart = input.subSequence(lastIndexOf+1, input.length());
LocalDateTime localDateTime = LocalDateTime.parse(parsable, FORMATTER);
Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.set(
localDateTime.getYear(),
localDateTime.getMonth().ordinal(),
localDateTime.getDayOfMonth(),
localDateTime.getHour(),
localDateTime.getMinute(),
0);
calendar.add(Calendar.SECOND, Integer.parseInt(TTTTPart.toString()));
StringBuilder toParse = new StringBuilder();
toParse.append(calendar.get(Calendar.YEAR) /* It gives 2016 but you what 2016, why */-1);
toParse.append("-").append(calendar.get(Calendar.MONTH) + 1 < 10 ? "0" : "")
.append(calendar.get(Calendar.MONTH)+1);
toParse.append("-").append(calendar.get(Calendar.DAY_OF_MONTH) < 10 ? "0" : "")
.append(calendar.get(Calendar.DAY_OF_MONTH));
toParse.append(" ").append(calendar.get(Calendar.HOUR_OF_DAY) < 10 ? "0" : "")
.append(calendar.get(Calendar.HOUR_OF_DAY));
toParse.append(":").append(calendar.get(Calendar.MINUTE) < 10 ? "0" : "")
.append(calendar.get(Calendar.MINUTE));
toParse.append(":").append(calendar.get(Calendar.SECOND) < 10 ? "0" : "")
.append(calendar.get(Calendar.SECOND));
localDateTime = LocalDateTime.parse(toParse, FORMATTER);
//Why 2015 and not 2016?
assertEquals("2015-01-01T23:59:59", localDateTime.toString());
}
it bugs me with is 2015 and not 2016, be aware that the solution is hammered to give you 2015 instead of 2016.
I'm still using Joda and no java8, but there it would be
Chronology lenient = LenientChronology.getInstance(ISOChronology.getInstance());
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:sssss").withChronology(lenient);
DateTime dateTime = DateTime.parse("2016-01-01 00:00:86399", FORMATTER);
assertEquals("2016-01-01T23:59:59", dateTime.toLocalDateTime().toString());
Maybe you can obtain the same behavior using:
DateTimeFormatter formatter =
DateTimeFormatter.ISO_LOCAL_DATE.withResolverStyle(ResolverStyle.LENIENT);

DateTimeFormatter zero out empty

is there a way to have a DateTimeFormatter like that
DateTimeFormatter.ofPattern("HH:mm")
and it should convert to a LocalDateTime and just zero out whats missing?
Actually on Joda there was DateTimeFormat which gave back a DateTime and not a exception. Is there any equivalent to that?
val formatter = org.joda.time.format.DateTimeFormat.forPattern(pattern)
formatter.parseDateTime(data).toDate
will always yield a real date no matter what the pattern is while on java8 it says its missing LocalDate.
Actually the pattern should be variable so that people could either insert HH:mm and dd.MM.yyyy and always get a LocalDateTime, that should be initalized / defaulted to 1970-01-01T00:00.
So doing:
// with pattern HH:mm
formatter.parse("00:00") should yield LocalDateTime.of(1970, 01, 01, 0, 0)
// with pattern YYYY-mm
formatter.parse("2016-11") should yield LocalDateTime.of(2016, 11, 01, 0, 0)
There are no built-in defaults. You have to provide the missing values.
// Parse HH:mm
LocalDateTime ldt1 = LocalTime.parse("12:34")
.atDate(LocalDate.of(1970, 1, 1));
System.out.println(ldt1); // Prints 1970-01-01T12:34
// Parse YYYY-mm
LocalDateTime ldt2 = YearMonth.parse("2016-11")
.atDay(1)
.atStartOfDay();
System.out.println(ldt2); // Prints 2016-11-01T00:00
Notice that you didn't even need a DateTimeFormatter for any of them.
UPDATE
If you must use DateTimeFormatter, then you can create one using DateTimeFormatterBuilder, where you can supply missing values using the parseDefaulting() method.
// Parse HH:mm
DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
.appendPattern("HH:mm") // other time fields default to 0, see "Resolving"
.parseDefaulting(ChronoField.EPOCH_DAY, 0) // short for 1970-01-01
.toFormatter();
LocalDateTime ldt1 = LocalDateTime.parse("12:34", formatter1);
System.out.println(ldt1); // Prints 1970-01-01T12:34
// Parse YYYY-mm
DateTimeFormatter formatter2 = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1) // see resolveDate()
.parseDefaulting(ChronoField.NANO_OF_DAY, 0) // short for 00:00:00.000000000
.toFormatter();
LocalDateTime ldt2 = LocalDateTime.parse("2016-11", formatter2);
System.out.println(ldt2); // Prints 2016-11-01T00:00
As for which fields are required for successful parsing, see:
DateTimeFormatter - Resolving
IsoChronology.resolveDate()
Just in case this solution works for me but I doubt it's not a "generic" answer since I only needed LocalDateTime and its also scala:
object MyDate {
def parse(text: CharSequence, formatter: DateTimeFormatter): MyDate = new MyDate(formatter.parse(text))
}
class MyDate(accessor: TemporalAccessor) {
private[this] def getOrDefault(field: TemporalField, default: Int): Int = {
if (accessor.isSupported(field)) accessor.get(field) else default
}
def toLocalDateTime: LocalDateTime = {
val year: Int = getOrDefault(ChronoField.YEAR, 1970)
val month: Int = getOrDefault(ChronoField.MONTH_OF_YEAR, 1)
val day: Int = getOrDefault(ChronoField.DAY_OF_MONTH, 1)
val hour: Int = getOrDefault(ChronoField.HOUR_OF_DAY, 0)
val minute: Int = getOrDefault(ChronoField.MINUTE_OF_HOUR, 0)
LocalDateTime.of(year, month, day, hour, minute)
}
}

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

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

Categories

Resources