Skip to content

Instantly share code, notes, and snippets.

@nikos-glikis
Last active August 29, 2015 14:16
Show Gist options
  • Save nikos-glikis/9e9bc983a88dbecfef9f to your computer and use it in GitHub Desktop.
Save nikos-glikis/9e9bc983a88dbecfef9f to your computer and use it in GitHub Desktop.
Convert mysql DateTime to java Calendar
/**
* Converts a mysql DateTime String to java Calendar
* @param dateString
* @return Calendar
*/
public static Calendar mysqlDateTimeToCalendar(String dateString)
{
try
{
//in my case I hade an . in the end of the date String.
if (dateString.indexOf(".") > -1) {
dateString = dateString.substring(0, dateString.indexOf("."));
}
StringTokenizer tokenizer = new StringTokenizer(dateString," ");
String datePart = tokenizer.nextToken();
String timePart = tokenizer.nextToken();
tokenizer = new StringTokenizer(datePart,"-");
String year = tokenizer.nextToken();
String month = tokenizer.nextToken();
String day = tokenizer.nextToken();
tokenizer = new StringTokenizer(timePart,":");
String hours = tokenizer.nextToken();
String minutes = tokenizer.nextToken();
String seconds = tokenizer.nextToken();
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, Integer.parseInt(year));
date.set(Calendar.MONTH, Integer.parseInt(month)-1);
date.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
date.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hours));
date.set(Calendar.MINUTE, Integer.parseInt(minutes));
date.set(Calendar.SECOND, Integer.parseInt(seconds));
return date;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment