Skip to content

Instantly share code, notes, and snippets.

@KeithNdhlovu
Last active July 14, 2016 11:41
Show Gist options
  • Save KeithNdhlovu/756479df166f2ae89344e8cab42e50d1 to your computer and use it in GitHub Desktop.
Save KeithNdhlovu/756479df166f2ae89344e8cab42e50d1 to your computer and use it in GitHub Desktop.
Create a date from string and the reverse
String dtStart = "2010-10-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// From Date to String
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = new Date();
String datetime = dateFormat.format(date);
System.out.println("Current Date Time : " + datetime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
private int calculateAge(String dateOfBirth) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try {
Date date = format.parse(dateOfBirth);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return getAge(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
} catch (ParseException e) {
e.printStackTrace();
Log.d(MainActivity.class.getSimpleName(), e.getMessage());
return 0;
}
}
public int getAge(int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment