Android date parsing (Extracting month and year ) - android

I want my app to parse the date in format "dd-MMM-yyyy". The date has been successfully parsed when I try to get month and get year it is giving other result. I inpued 06-sep-2014 as date. But when I try to extract month and year from the parsed date it is showing 8 for month instead of 9 and 114 for year instead of 2014.
logcat output
6
8
114
Here's my code
String date1 = "06 sep 2014";
SimpleDateFormat format1 = new SimpleDateFormat("dd MMM yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("d MMM yyyy");
Date date;
try {
if (date1.length() == 11) {
date = format1.parse(date1);
} else {
date = format2.parse(date1);
}
int day=date.getDate();
int mon1=date.getMonth();
int year1=date.getYear();
System.out.println("date is:"+ date);
System.out.println(day);
System.out.println(mon1);
System.out.println(year1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public final class DateParseDemo {
public static void main(String[] args){
final DateFormat df = new SimpleDateFormat("dd MMM yyyy");
final Calendar c = Calendar.getInstance();
try {
c.setTime(df.parse("06 sep 2014"));
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + (c.get(Calendar.MONTH)));
System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
Year = 2014
Month = 8
Day = 6
And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Because date.getyear Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Maybe, You can use for example;
int year1=date.getYear();
System.out.println(year1+1900);

Using the Date class, it gives you the year starting from 1900. A better way to get what you want is using the Calendar class. See http://developer.android.com/reference/java/util/Date.html#getYear()

Related

How to convert db2 date to YYYMMDD in android

I'm receiving a db2 date as 1200703 to the mobile as the response. I need to convert that date to a readable format as YYYYMMDD. How can I do that from the android side?
This is not db2 date format, but rather the way some systems store a date. It's so called CYYMMDD integer format.
YEAR = 1900 + 100*C + YY
MONTH = MM
DAY = DD
The date string, 1200703 is in CYYMMDD format. This format was (I'm not sure if it is still in use as the last time when I used DB2 was in 2008) used by DB2.
In order to calculate the year, you need to use the following formula:
Year = 100 * C + 1900 + YY e.g. for CYY = 120, the value of year = 100 * 1 + 1900 + 20 = 2020.
Once you convert the CYY part into yyyy format, you can use date-time formatting API as shown below:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class Main {
public static void main(String args[]) {
// Given date string
String dateStr = "1200703";
// Convert the given date string into yyyyMMdd format
int c = Integer.parseInt(dateStr.substring(0, 1));
int yy = Integer.parseInt(dateStr.substring(1, 3));
int year = 100 * c + 1900 + yy;
String dateStrConverted = String.valueOf(year) + dateStr.substring(3);
// ########## For Java 8 onwards ##############
// Define a formatter
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate localDate = LocalDate.parse(dateStrConverted, dtf);
System.out.println("Default format: " + localDate);
// Printing the date in a sample custom format
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("EEE MMM dd yyyy");
String strDate1 = dtf1.format(localDate);
System.out.println(strDate1);
// ############################################
// ############## Before Java 8 ###############
// Define a formatter
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date utilDate = null;
try {
utilDate = sdf.parse(dateStrConverted);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Default format: " + utilDate);
// Printing the date in a sample custom format
SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd yyyy");
String strDate2 = sdf1.format(utilDate);
System.out.println(strDate2);
// ############################################
}
}
Output:
Default format: 2020-07-03
Fri Jul 03 2020
Default format: Fri Jul 03 00:00:00 BST 2020
Fri Jul 03 2020
Note: I recommend you use the modern date-time API. If the Android version which you are using is not compatible with Java-8, I suggest you backport using ThreeTen-Backport library. However, if you want to use the legacy API, you can use do so as shown in the answer.

How to get date which is the sum of any previous date to 7 days next date?

I've a previous date from current date which is saved in database and need to get date 7 days next date. How can i get it?
For example:
i've date 1461560032085 milliseconds. How can i get 7 days next date?
It is very simple to use Calendar class
Calendar calendar = Calendar.getInstance();
calendar.setTime(your_current_date);
calendar.add(Calendar.DAY_OF_YEAR, +7);
Date newDate = calendar.getTime();
1 day = 86400000 milliseconds
So 7 days after "1461560032085" will be = 1461560032085 + 86400000 * 7
Hope this helps!
To calculate 7 days after the current day you should do the following:
nextWeek = yourdate + 7*24*60*60*1000
public static String getAdded_date(String previous_date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(previous_date));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_WEEK, 7); // number of days to add, can also use Calendar.DAY_OF_MONTH in place of Calendar.DATE
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
String output = sdf1.format(c.getTime());
return output;
}
private int getaddedDate(int previousdate)
{
return previousdate + TimeUnit.DAYS.toMillis(7);
}

String Date to Milliseconds Android [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate date/time difference in java
how would a future date such as Sat Feb 17 2012 be converted into milliseconds in java that can then be subtracted from the current time in milliseconds to yield time remaining until that future date.
The simplest technique would be to use DateFormat:
String input = "Sat Feb 17 2012";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
long millisecondsFromNow = milliseconds - (new Date()).getTime();
Toast.makeText(this, "Milliseconds to future date="+millisecondsFromNow, Toast.LENGTH_SHORT).show();
A more difficult technique (that basically does what DateFormat does for you) involves parsing it yourself (this would not be considered best practice):
String input = "Sat Feb 17 2012";
String[] myDate = input.split("\\s+");
int year = Integer.parseInt(myDate[3]);
String monthString = myDate[1];
int mo = monthString.equals("Jan")? Calendar.JANUARY :
monthString.equals("Feb")? Calendar.FEBRUARY :
monthString.equals("Mar")? Calendar.MARCH :
monthString.equals("Apr")? Calendar.APRIL :
monthString.equals("May")? Calendar.MAY :
monthString.equals("Jun")? Calendar.JUNE :
monthString.equals("Jul")? Calendar.JULY :
monthString.equals("Aug")? Calendar.AUGUST :
monthString.equals("Sep")? Calendar.SEPTEMBER :
monthString.equals("Oct")? Calendar.OCTOBER :
monthString.equals("Nov")? Calendar.NOVEMBER :
monthString.equals("Dec")? Calendar.DECEMBER : 0;
int day = Integer.parseInt(myDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, mo, day);
long then = c.getTimeInMillis();
Time current_time = new Time();
current_time.setToNow();
long now = current_time.toMillis(false);
long future = then - now;
Date d = new Date(future);
//TODO use d as you need.
Toast.makeText(this, "Milliseconds to future date="+future, Toast.LENGTH_SHORT).show();
Firts, you must parse you String to get its Date representation. Here are examples and some docs.
Then you shoud call getTime() method of your Date.
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
long futureTime = 0;
try {
Date date = format.parse("Sat Feb 17 2012");
futureTime = date.getTime();
} catch (ParseException e) {
Log.e("log", e.getMessage(), e);
}
long curTime = System.currentTimeMillis();
long diff = futureTime - curTime;
Pass year, month and day of the future date in the date of this code and variable diff will give the millisecond time till that date,
Date date = new GregorianCalendar(year, month, day).getTime();
Date today = new Date();
long diff = date.getTime() - today.getTime();
You can simply call the getTime() method of date object. please follow through the sample below
import java.util.Date;
public class Test {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
System.out.println(new Date("Sat Feb 17 2012").getTime());
}
}
try { String str_date="11-June-07";
SimpleDateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = (Date) formatter.parse(str_date);
Log.i("test",""+date);
} catch (Exception e)
{System.out.println("Exception :"+e); }
Date d = new Date();
long time = d.getTime();
long timeDiff = time - lastTime;
//timeDiff will contain your value.
//import these two,
//import java.text.SimpleDateFormat;
//import java.util.Date;

Android: Calendar add days including month and year

I have a problem. I am using this code to "increase" or "decrease" one day. "value" is 1 or -1. I have tried c.add(Calendar.DAY_OF_MONTH, value); and c.add(Calendar.DATE, value); The problem is:
if value = 1, it increases day by 1 and month and year don't budge at all and remain same.
if value = -1, it decreases day by 1 and after 30 days it decrease the year.
I have tried everything but could not understand the behavior. I need to increase or decrease the whole date like it happens in MYSQL, not just date or month or year.
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(mDate));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, value);
sdf = new SimpleDateFormat("dd/mm/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
String newDtString = sdf.format(resultdate);
You can try
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + value);
You'd also have to handle end cases when it's first or last day of year
Java handles this for you. Example:
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
calendar.setTimeZone(TimeZone.getDefault());
try {
calendar.setTime(sdf.parse("31 December 2015"));
} catch (ParseException e̋̋) { }
System.out.println(sdf.format(calendar.getTime()));
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + 1);
System.out.println(sdf.format(calendar.getTime()));
Prints:
31 December 2015
01 January 2016

Calculating date certain period from now

I have a start date (day, month, year) and need the date say 4 weeks from that date. How can I calculate that? I know how to find the difference between two dates using Calendar so I assume I'm not too far from the answer... Thank you!!!
edit:
This is the final code I wound up using. It returns a String whose value is a date span formatted "MM/dd/YYYY - MM/dd/YYYY"
#SuppressLint("SimpleDateFormat")
private String getSessionDate(int position) {
MySession ms = mSessionList.get(position);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(ms.getStartYear(), ms.getStartMonth(), ms.getStartDay());
Date startDate = calendar.getTime();
String durationString = ms.getDurationString(); // Format is "## weeks"
int i = 0;
while (Character.isDigit(durationString.charAt(i))) {
i++;
}
int weeks = Integer.parseInt(durationString.substring(0, i));
calendar.add(Calendar.WEEK_OF_YEAR, weeks);
return (format.format(startDate) + " - " + format.format(calendar.getTime()));
}
You can use Calender instance for that.
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentdate);
calendar.add(Calendar.DAY_OF_YEAR, no_of_days)
Date newDate = calendar.getTime();
You can calculate the date by adding or subtracting the no of days
Example :
Get date after 1 week
calendar.add(Calendar.DAY_OF_YEAR, 7);
Get date before 1 week
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date date=null;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = originalFormat.parse(strDate); // strDate is your date from which you want to get date after 4 weeks
} catch (Exception e) {
e.printStackTrace();
}
long timeFor4week=4*7*24 * 60 * 60 * 1000; /// here 24*60*60*1000 =24 hours i.e 1 day
long timeAfter4week=date.getTime()+timeFor4week;
String finalDateString=originalFormat.format(new Date(timeAfter4week));
So you can get day after 4 weeks.

Categories

Resources