Date conversion into different data type
Most of times, we've busy with converting one data type into another data type and validations. That's a developer's life. Actually it's makes life interesting.
This is old, anyhow I post here. Just try it.
Convert current time to long Timestamp.
public static long getCurrentTimeStamp(Context context) {
long timestamp = 0;
try {
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMMM-yyyy hh:mm ss a");
timestamp = c.getTime().getTime();
} catch (Exception e) {
//handle exception
}
return timestamp;
}
Convert Date into String
public static String convertDate(Date date) {
String format = "dd-MMM-yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
String stringDate = "";
try {
stringDate = sdf.format(date);
} catch (Exception e) {
//handle exception
}
return stringDate;
}
Convert Timestamp into String
public static String getDateString(long timeStamp) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
Date netDate = (new Date(timeStamp));
return sdf.format(netDate);
} catch (Exception ex) {
//handle exception
}
}
Convert String into Date
public static Date stringToDate(String str) {
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("hh:mm a MMM dd");
try {
date = format.parse(str);
System.out.println(date);
} catch (ParseException e) {
//handle exception
}
return date;
}
This is old, anyhow I post here. Just try it.
Convert current time to long Timestamp.
public static long getCurrentTimeStamp(Context context) {
long timestamp = 0;
try {
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMMM-yyyy hh:mm ss a");
timestamp = c.getTime().getTime();
} catch (Exception e) {
//handle exception
}
return timestamp;
}
Convert Date into String
public static String convertDate(Date date) {
String format = "dd-MMM-yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
String stringDate = "";
try {
stringDate = sdf.format(date);
} catch (Exception e) {
//handle exception
}
return stringDate;
}
Convert Timestamp into String
public static String getDateString(long timeStamp) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
Date netDate = (new Date(timeStamp));
return sdf.format(netDate);
} catch (Exception ex) {
//handle exception
}
}
Convert String into Date
public static Date stringToDate(String str) {
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("hh:mm a MMM dd");
try {
date = format.parse(str);
System.out.println(date);
} catch (ParseException e) {
//handle exception
}
return date;
}
Comments