Java date parsing without separators? - java

In my program i am parsing a string date(frmDateStr) with separators as below and getting fromDate
which I use for my further comparisons.
String frmDateStr = "12/25/2013";
Date fromDate = formatter.parse(frmDateStr);
Now if i pass frmDateStr = "12252013" or "122513"(2 digit year) i want to get the same result.
But i got parse exception.
So please let me know how to get date value while the string is without separators and short year?
Thanks in advance
Yash

Use this code, it will help
String dateFormat = "MMddyyyy";
if (dateString.indexOf("/") != -1)
{
dateFormat = "MM/dd/yyyy";
}
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
System.out.print(formatter.parse(dateString));
your input is dateString

As the other Answers say, you must define a formatter that fits your data.
java.time
Java 8 and later come bundled with the new java.time framework (Tutorial). These new classes supplant the old java.util.Date/.Calendar & java.text.SimpleDateFormat.
Also, java.time includes a class LocalDate to represent simply a date only without time-of-day and time zone, as you have in the Question.
String input = "12252013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMddyyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Dump to console.
System.out.println( "localDate : " + localDate );
When run.
localDate : 2013-12-25

import java.util.Random;
/**
* Created by vapa1115 on 9/27/2018.
*/
public class UtmUtil {
public static String getSourceAddress(String sourceAddressValue) {
if(sourceAddressValue==null) {
Random r = new Random();
sourceAddressValue = r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
}else{
Random r = new Random();
int ind = sourceAddressValue.lastIndexOf(".");
String randomValue=r.nextInt(256)+"";
if(randomValue.length()>3){
randomValue=randomValue.substring(0,2);
}
sourceAddressValue= new StringBuilder(sourceAddressValue).replace(ind, ind+1,"."+randomValue).toString();
}
return sourceAddressValue;
}
public static void main(String sd[]){
getSourceAddress("192.168.0");
}
}

Create your own SimpleDateFormat instance and use it to read date from a string:
All necessary information can be found here:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Related

Android convert numbers into date format

I am storing month and year in my android database. I want to fetch it and convert it to date format so that I can match it with current month and year present in array. Im fetching it through ArrayList but how to convert in date format and match?
private ArrayList<String> getGspApprovedMonthData() {
List<Date> dates = new ArrayList<>(gspApprovedMonth.size());
gspApprovedMonth.clear();
SqlDataStore sd = new SqlDataStore(this);
sd.open();
String gspQuery = " SELECT * FROM "+ TABLE_GSP_APPROVED_DATA;
Cursor gspCu = sd.getData(gspQuery);
if(gspCu.moveToFirst()){
do {
String gspMonth = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_MONTH));
String gspYr = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_YEAR));
gspApprovedMonth.add(gspMonth+gspYr);
} while (gspCu.moveToNext());
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (String dateString : gspApprovedMonth) {
try {
dates.add(sdf.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
}
gspCu.close();
sd.close();
return gspApprovedMonth;
}
java.time
The java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API in Mar 2014. Since then, it is highly recommended to stop using the legacy date-time API.
Solution using java.time, the modern date-time API:
The java.time API provides you with Year that you can combine with a month using Year#atMonth to get a YearMonth. A YearMonth can be compared with another using its methods like YearMonth#isAfter, YearMonth#isBefore etc.
Demo:
import java.time.Year;
import java.time.YearMonth;
class Main {
public static void main(String[] args) {
// Sample year and month strings
String strYear = "2022";
String strMonth = "9";
YearMonth ym = Year.of(Integer.parseInt(strYear))
.atMonth(Integer.parseInt(strMonth));
System.out.println(ym);
// Comparing two instances of YearMonth
YearMonth currentYm = YearMonth.now();
if (ym.isAfter(currentYm))
System.out.println(ym + " is after " + currentYm);
else
System.out.println(ym + " is before or equal to " + currentYm);
}
}
Output:
2022-09
2022-09 is before or equal to 2023-01
ONLINE DEMO
How to implement it in your code?
List<YearMonth> yearMonths = new ArrayList<>(gspApprovedMonth.size());
// ...
if(gspCu.moveToFirst()){
do {
String gspMonth = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_MONTH));
String gspYr = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_YEAR));
yearMonths.add(Year.of(Integer.parseInt(gspYr))
.atMonth(Integer.parseInt(gspMonth)));
// ...
} while (gspCu.moveToNext());
}
// ...
Learn more about the modern Date-Time API from Trail: Date Time.

Possible to create a Java.time.LocalDate object from a String?

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.");
}
}

Previous Calendar date not coming as expected, need a workaround

The following code gives incorrect output - 29/01/2015, should give 29/12/2015.
Please provide a work around to get the correct value.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CheckTime{
public static void main(String... x) throws Exception{
DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
Date date = formatter.parse("31/12/2015");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -1);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(day+"/"+month+1+"/"+year);
}
}
Wrong Format Pattern
As the comments discuss, the format pattern used lowercase mm (minute-in-hour) where it should have used uppercase MM (month-in-year).
java.time
Java 8 and later comes with the java.time framework that supplants the old date-time classes used in the Question. These new classes are a vast improvement. Avoid the old.
Among the new classes is one to track a date-only value without time-of-day or time zone: LocalDate.
Standard ISO 8601 formats are used by default in parsing and generating String representations of date-time values. As your string inputs are in a different format, we must specify a coded pattern.
String input = "31/12/2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "dd/MM/yyyy" );
LocalDate localDate = LocalDate.parse ( input, formatter );
We can easily find the previous and next days. Note the use of immutable objects pattern. Rather than alter member fields of an object, we create a new object based on the old object’s values. Much safer for value objects such as date-time.
LocalDate previousDay = localDate.minusDays ( 1 );
LocalDate nextDay = localDate.plusDays ( 1 );
Dump to console.
System.out.println ( "localDate: " + localDate + " previousDay: " + previousDay + " nextDay: " + nextDay );
localDate: 2015-12-31 previousDay: 2015-12-30 nextDay: 2016-01-01

How to obtain elapsed years from string

I have the string date "3.9.1991". And I want to obtain how many years have passed since the date. For example 23. How can I achieve it using Calendar or Date?
EDIT:
I have been trying this:
private String parseVkBirthday(String birthdayString) {
// 3.9.1991
SimpleDateFormat formatter = new SimpleDateFormat("d.M.yyyy");
String formattedDate = null;
Calendar date = Calendar.getInstance();
int year = 0;
try {
Date currentDate = new Date();
Date birthdayDate = formatter.parse(birthdayString);
Log.d(LOG_TAG, "year1 = " + currentDate.getTime() + " year2 = " + birthdayDate.getTime());
long diff = currentDate.getTime() - birthdayDate.getTime();
birthdayDate.setTime(diff);
date.setTime(birthdayDate);
year = date.get(Calendar.YEAR);
} catch (ParseException e) {
e.printStackTrace();
}
return "" + year;
}
But it returns me 1993.
Answer:
There are while 3 ways for solving this problem:
1) As codeaholicguy answered, we can use Joda-Time library(what I prefer for Android).
2) As Basil Bourque answered, we can use ThreeTen-Backport library for using java.time classes from java 8.
3) And we can use java 8 and classes from java.time.
Thanks to everyone.
Use SimpleDateFormat and Period of Joda-Time library, example below:
String pattern = "dd.MM.yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date date = format.parse("3.9.1991");
System.out.println(date);
Period period = new Period(date.getTime(), (new Date()).getTime());
System.out.println(period.getYears());
String fullDate="3.9.1991";
String[] splitDate=fullDate.split(".");
int year=Integer.parseInt(splitDate[2]);
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int passedYears=currentYear-year;
Calendar.YEAR can be used to add or subtract year from current date in the same fashion we added days and month into date.
http://javarevisited.blogspot.in/2012/12/how-to-add-subtract-days-months-years-to-date-time-java.html
sample program:
import java.util.Calendar;
public class Years {
public static void main(String[] args) {
//create Calendar instance
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//add year to current date using Calendar.add method
now.add(Calendar.YEAR,1);
System.out.println("date after one year : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
//substract year from current date
now =Calendar.getInstance();
now.add(Calendar.YEAR,-100);
System.out.println("date before 100 years : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
}
}
http://forgetcode.com/Java/1568-Adding-or-Subtracting-Years-to-Current-Date#
Based on example code by xrcwrn with the Joda-Time 2.8 library:
// get the current year with #xrcwm's code
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
DateTime myDateTime = new DateTime(thedate.getTime()); // joda DateTime object
// get he current date
DateTime currentDateTime = new DateTime();
// get the years value
long years = Years.between(currentDateTime, myDateTime).getYears()
The code above should give you the correct value. Mind you, this code may have some syntax errors.
As a side note, Java 8 has a time package which seems to provide more of the same functionality.
java.time
The new java.time package in Java 8 and later supplants the old java.util.Date/.Calendar & SimpleTextFormat classes.
First parse the string using new DateTimeFormatter class. Do not use SimpleTextFormat. And read the doc as there may be subtle differences in the symbol codes between the old and new classes.
Get today's date, to calculate elapsed years. Note that we need a time zone. Time zone is crucial in determining a date. A new day dawns earlier in Paris, for example, than it does in Montréal.
The Period class considers a span of time as a number of years, months and days not tied to any points on the timeline.
The between method uses the "Half-Open" approach common to date-time handling. The beginning is inclusive while the ending is exclusive.
The default formatting of java.time follows the ISO 8601 standard. Apply formatter if you wish a different string representation of your date-time values.
String input = "3.9.1991" ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d.M.yyyy") ;
LocalDate then = LocalDate.parse( input, formatter ) ;
ZoneId zone = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( zone ) ; // Specify time zone to get your locality’s current date.
Period period = Period.between( then , today ) ;
int years = period.getYears() ;
System.out.println( "Between " + then + " and " + today + " is " + years + " years.");
Between 1991-09-03 and 2015-07-09 is 23 years.
Joda-Time
Android currently lacks Java 8 features. So you cannot use java.time. Unless perhaps the ThreeTen-Backport project (a) supports the classes used in the above example and (b) works on Android (I do not know about either).
Alternatively, you can use Joda-Time, the third-party library that inspired java.time. The Joda-Time code version of the above code example would be very similar. In this case, java.time and Joda-Time parallel one another with similar classes.
Calendar mydate = new GregorianCalendar();
String mystring = "3.9.1991";
Date thedate = new SimpleDateFormat("d.m.yyyy", Locale.ENGLISH).parse(mystring);
mydate.setTime(thedate);
//breakdown
System.out.println("year -> "+mydate.get(Calendar.YEAR));
Reference

Trying to parse the time

I have String
String aa="01:30";
String hh=aa.substring(0,2);
String mm=aa.substring(3,5);
I am trying to parse the seperated values by using
int hh=Integer.parseInt(hhs);
int mm=Integer.parseInt(mms);
The out put is 1 and 30 How can I solve to get output as it is like 01 & 30?
Thanks in advance
An integer can't store leading zeroes. If you are getting 3 for mm though it indicates you have another problem, as that should resolve to 30
Saying you want an integer value and you want a leading zero is contradictory. Numeric data types have just the number value; only a String representation of that number has a leading zero.
So you need to decide… Do you want:
An integer (example: 1)
A String (example: 01)
A time (example: 01:30)
Generally if working with date-time values, you should treat them as such. Rather than use the notoriously troublesome java.util.Date/Calendar classes, use either the Joda-Time library or the new java.time.* classes in Java 8.
Example code using Joda-Time 2.3.
String input = "01:30";
LocalTime localTime = new LocalTime( input );
int hourOfDay = localTime.getHourOfDay();
int minuteOfHour = localTime.getMinuteOfHour();
Dump to console…
System.out.println( "localTime: " + localTime );
System.out.println( "hourOfDay: " + hourOfDay );
System.out.println( "minuteOfHour: " + minuteOfHour );
When run…
localTime: 01:30:00.000
hourOfDay: 1
minuteOfHour: 30
You can always do formatting
like this
DecimalFormat df=new DecimalFormat("00");
System.out.println("HH "+df.format(hh));
That will give 01 as the output.
String aa="01:30";
String hhs=aa.substring(0,2);
String mms=aa.substring(3,5);
int hh=Integer.parseInt(hhs);
int mm=Integer.parseInt(mms);
String hh_formatted = String.format(Locale.ENGLISH,"%02d", hh);
String mm_formatted = String.format(Locale.ENGLISH,"%02d", mm);
Using above only you can get your desired output in string format.
Time specific things should be done with Date()..
SimpleDateFormat inFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat outHourFormat = new SimpleDateFormat("HH");
SimpleDateFormat outMinFormat = new SimpleDateFormat("mm");
String outHour = null;
String outMinute = null;
Date input;
try {
input = inFormat.parse("03:30");
outHour = outHourFormat.format(input);
outMinute = outMinFormat.format(input);
} catch (ParseException e) {
e.printStackTrace();
}
// now you got two Strings: outHour & outMinute in correct form.

Categories

Resources