Convert Data format using SimpleDateFormat - java

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

Related

How to Get next monthyear(YYYYMM) by passing any monthyear(YYYYMM) in Java?

Example, I have a monthyear on String, like this:
202108
And I want to next month by passing above month in below format:
202109
What is the best way to do this?
Java 8+ ⇒ java.time.YearMonth:
public static void main(String[] args) throws Exception {
// create a formatter for the String format you are using
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM");
// use it in order to parse the String to a YearMonth
YearMonth yearMonth = YearMonth.parse("202108", dtf);
// add a month to have the next one
YearMonth nextYearMonth = yearMonth.plusMonths(1);
// and print it using the formatter
System.out.println(nextYearMonth.format(dtf));
}
Output:
202109
If you want it as a method/function, then try something like
public static String getYearMonthAfter(String month) {
// create a formatter for the String format you are using
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM");
// use it in order to parse the String to a YearMonth
YearMonth yearMonth = YearMonth.parse(month, dtf);
// add a month to have the next one
YearMonth nextYearMonth = yearMonth.plusMonths(1);
// and return the resulting String by means of the formatter
return nextYearMonth.format(dtf);
}
SimpleDateFormat and Calendar can help you a lot.
public static String getNextMonth(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Calendar cal = Calendar.getInstance();
try{
cal.setTime(sdf.parse(s));
} catch (ParseException e) {
e.printStackTrace();
return "";
}
cal.add(Calendar.MONTH, 1);
return sdf.format(cal.getTime());
}
You can use add function in Calendar class to add month
public String getNextMonth(String time){
DateFormat sdf = new SimpleDateFormat("yyyyMM");
Date dt = sdf.parse(time);
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.MONTH, 1); //adding a month
String req_date = sdf.format(c.getTime());
return req_date;
}

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

Android DateFormat for AM/PM differs between devices

I am formatting dates like this:
public static String toFormattedDate(#NonNull Time time, String toFormat) {
mDateFormat = new SimpleDateFormat(toFormat);
Date date = new Date();
date.setTime(time.toMillis(true));
return mDateFormat.format(date);
}
and the format I am using is:
public static final String TIME = "hh:mm a";
But it differs between the two devices that I am using for testing...
Nexus 10:
Nexus 5X:
How can I format it uniformly between devices?
You may either have to use either the 24 hour value to determine what to append so that you can add the format you desire.
public static final String TIME = "hh:mm";
and then
String ampm = Integer.parseInt(time.valueOf("hh")) >= 12 ? "PM" : "AM";
...
return mDateFormat.format(date)+" "+ampm;
Or if you feel lazy you can just do without changing the value of TIME:
return mDateFormat.format(date).toUpperCase().replace(".","");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String currentDateandTime = sdf.format(new Date());

Parse date time format "2013-12-09 12:14:09.994844+10" in Android

I need to parse string value of data = "2013-12-09 12:14:09.994844+10" with SimpleDateFormat.
I'm using format = "yyyy-MM-dd HH:mm:ss.SSSSSSZ", but it's not working.
How can I solve this problem?
public class Test {
public static final String FORMAT1 = "hh:mm aa dd.MM.yyyy";
public static final String FORMAT2 = "yyyy-MM-dd HH:mm:ss.SSSSSSZ";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Time = "
+ getDate("2013-12-09 12:14:09.994844+10",
DateTimeUtils.FORMAT2, DateTimeUtils.FORMAT1));
}
public static String getDate(String inputDate, String inputFormat,
String outputFormat) {
String strDate = "";
SimpleDateFormat sdfInput = new SimpleDateFormat(inputFormat,
Locale.getDefault());
SimpleDateFormat sdfOutput = new SimpleDateFormat(outputFormat,
Locale.getDefault());
if (inputDate != null) {
Date date;
try {
date = sdfInput.parse(inputDate);
strDate = sdfOutput.format(date);
} catch (ParseException e) {
strDate = "";
e.printStackTrace();
}
}
return strDate.toUpperCase();
}
}
In Java SE 7 to format a timezone with one sign and two digits use the letter 'X'. For example: "yyyy-MM-dd HH:mm:ss.SSSSSSX". The javadoc can be found here.
In Android however the letter 'X' is not supported but you may add two extra zeros to the date string in order to use 'Z'. For example: "2013-12-09 12:14:09.994844+1000" will be correctly parsed. The javadoc for Android can be found here.
SimpleDateFormat can't deal with microseconds.
You need to strip out the extra 3 digits.
like this:
data = data.substring(0, data.length()-4)+"Z";

How to find out future timestamp value in GWT?

I have few timestamp format
time stamp format contains YYYY MM DD hh mm ss S AM/PM CountryName/CityName(zone)
YYYY-MM-DD HH:mm:ss.S
YYYY-MM-DD HH:mm:ss.S AM/PM
YYYY-MM-DD HH:mm:ss.S AM/PM z
YYYY-MM-DD HH:mm:ss.z
I want to do validation on timestamp value, If time stamp value is future value (or greater than existing) then want to show.notification message to user.
For Date format I have written following code which works to check Future date
DateTimeFormat df = DateTimeFormat.getFormat(dateFormat);
Date updateDate = df.parseStrict(newDateValue);
Date synchronizedDate = df.parseStrict(synchronizedDB_DateValue);
boolean isFutureDate = updateDate.after(synchronizedDate);
if (isFutureDate ) {
// send notification
}
else {
// do nothing
}
EDIT:
Following code only works for timestamp format = YYYY-MM-DD HH:mm:ss.S
String timestampFormat = "YYYY-MM-DD HH:mm:ss.S"; // It works
//String timestampFormat = "YYYY-MM-DD HH:mm:ss.S AM/PM";
//String timestampFormat = "YYYY-MM-DD HH:mm:ss.S AM/PM z"
//String timestampFormat = "YYYY-MM-DD HH:mm:ss.S z ";
String newTimestampFormat= timestampFormat.replaceAll("-", ".");
newTimestampFormat = newTimestampFormat.replace("YYYY", "yyyy");
newTimestampFormat = newTimestampFormat.replace("AM/PM", "a");
DateTimeFormat df = DateTimeFormat.getFormat(newTimestampFormat);
Date updateDate = df.parse(newTimeStampValue); // UPDATED VALUE = 2013.08.21 00:00:00.123
Date synchronizedDate = df.parseStrict(synchronizedDB_DateValue); // current or old db value = 2013.07.11 00:00:00.123
boolean isFutureTimestamp = updateDate.after(synchronizedDate);
if (isFutureTimestamp ) {
// send notification
}
else {
// do nothing
}
What changes I need to do for all other time-stamp format ?
Thanks in advance.
This is my solution and It Works :)
private boolean function isFutureTimestamp(){
String gwtTimestampFormat = convertToGwtTimeStampFormat(timestampFormat);
// timestampFormat = YYYY-MM-DD HH:mm:ss.S AM/PM z
// gwtTimestampFormat = yyyy.MM.dd HH:mm:ss.S a z
DateTimeFormat df = DateTimeFormat.getFormat(gwtTimestampFormat);
String newlyUpdatedTimestampValue = convertToGwtTimeStampFormat(timestampValue);
Date updatedDateTime = df.parse(newlyUpdatedTimestampValue);
String currentTimestamp = convertToGwtTimeStampFormat(currentTimestampValue);
Date currentDateTime = df.parse(currentTimestamp);
boolean isFutureTimestamp = updatedDateTime.after(currentDateTime);
return isFutureTimestamp;
}
private String convertToGwtTimeStampFormat(String gwtTimestampFormat) {
if (gwtTimestampFormat != null && gwtTimestampFormat.length() > 20) { // "2012-12-23 23:12:32.2".length= 21
gwtTimestampFormat = gwtTimestampFormat.replace("-", ".");
gwtTimestampFormat = gwtTimestampFormat.replace("YYYY", "yyyy");
gwtTimestampFormat = gwtTimestampFormat.replace("DD", "dd");
gwtTimestampFormat = gwtTimestampFormat.replace("AM/PM", "a");
return gwtTimestampFormat;
}
else {
return "";
}
}
Try using Apache DateUtils. (doc is here)
Use parseDate method(s) as it supports a wide variety of formats and can be possibly used in many other places too.
For example while using parseDate you can feed all these time stamp patterns as a string array to the following method:
public static Date parseDate(String str, String[] parsePatterns) throws ParseException
to receive Date objects.
And with this you can compare dates just like you compare numbers:
public static int truncatedCompareTo(Date date1, Date date2, int field)
This returns you a negative integer, zero, or a positive integer as the first date is less than, equal to, or greater than the second.
Notice that these methods are static so you can invoke these without needing to create a DateUtils objects. Just use DateUtils.yourMethod(yourArgs) once you have imported the jar.

Categories

Resources