Skip to content

Instantly share code, notes, and snippets.

@NeerajItdose
Created March 30, 2020 09:48
Show Gist options
  • Save NeerajItdose/a3fa6f1df4db498fa3ed25683d0bcb1f to your computer and use it in GitHub Desktop.
Save NeerajItdose/a3fa6f1df4db498fa3ed25683d0bcb1f to your computer and use it in GitHub Desktop.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DateConversion {
public static String convertToFullDate(String date) {
String newDate;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
try {
Date d = dateFormat.parse(date);
SimpleDateFormat timeFormat = new SimpleDateFormat("dd MMM", Locale.getDefault());
newDate = timeFormat.format(d);
} catch (ParseException e) {
return "";
}
return newDate;
}
public static long getLongDate(String strDate) {
long duration = 0;
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date = timeFormat.parse(strDate);
duration = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return duration;
}
public static String convertDateToString(long milliSecond) {
return convertDateToString(milliSecond, "yyyy-MM-dd");
}
public static String convertDateToString(Date date) {
return getFormatedDate(date, "yyyy-MM-dd");
}
public static String getFormatedDate(Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault());
return dateFormat.format(date);
}
public static String convertTimeToString(int hours, int minutes, String format) {
return convertDateToString(convertTimeToCalender(hours, minutes).getTimeInMillis(), format);
}
public static String convertDateToString(int year, int month, int date, String format) {
return convertDateToString(convertDateToCalender(year, month, date).getTimeInMillis(), format);
}
private static Calendar convertDateToCalender(int year, int month, int date) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, date);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, date);
return calendar;
}
private static Calendar convertTimeToCalender(int hours, int minutes) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, minutes);
return calendar;
}
public static String convertDateToString(long milliSecond, String format) {
SimpleDateFormat timeFormat = new SimpleDateFormat(format, Locale.getDefault());
return timeFormat.format(milliSecond);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment