Skip to content

Instantly share code, notes, and snippets.

@magnet88jp
Last active August 29, 2015 14:23
Show Gist options
  • Save magnet88jp/2d4b9fa653e5ba5ffc74 to your computer and use it in GitHub Desktop.
Save magnet88jp/2d4b9fa653e5ba5ffc74 to your computer and use it in GitHub Desktop.
convert datetime format from string
/**
* convert datetime from string
* @param String datetimeStr : datetime formart string. for example 2015/6/18 11:11
* @return Datetime :
*/
public static Datetime convertDatetimeFromStr( String datetimeStr ) {
Date dateConv = null;
Time timeConv = Time.newInstance(0, 0, 0, 0);
List<String> dt = String.ValueOf(datetimeStr).split('\\-|\\/|\\s|T', 4);
if(dt.size() > 2) {
dateConv = Date.newInstance(Integer.ValueOf(dt.get(0)), Integer.ValueOf(dt.get(1)), Integer.ValueOf(dt.get(2)));
if(dt.size() > 3) {
List<String> tm = String.valueOf(dt.get(3)).split(':', 3);
if(tm.size() == 3) {
timeConv = Time.newInstance(Integer.valueOf(tm.get(0)),Integer.valueOf(tm.get(1)),Integer.valueOf(tm.get(2)),0);
} else if (tm.size() == 2) {
timeConv = Time.newInstance(Integer.valueOf(tm.get(0)),Integer.valueOf(tm.get(1)),0,0);
}
}
}
return (dateConv != null) ? Datetime.newInstance(dateConv, timeConv) : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment