Monday, August 22, 2016

Android - Formatting Date and Time.



Date and Time formatting Cheat Sheet

SymbolMeaningType Type
GEraText GG->AD
YYearNumber yy -> 03, yyyy -> 2003
MMonthText or Number M -> 7, MM -> 07, MMM -> Jul , MMMM -> July                 
dDay in monthNumber d -> 3 , dd -> 03
hHour (1-12, AM/PM)Number h -> 3 , hh -> 03
HHour (0-23)Number H -> 15 , HH -> 15
kHour (1-24)Number k -> 3 , kk -> 03
KHour (0-11 AM/PM) Number K -> 15 , KK -> 15
mMinuteNumber m -> 7 , m -> 15 , mm -> 15
sSecondNumber s -> 15 , ss -> 15
SMillisecond (0-999)Number SSS -> 007
EDay in weekText EEE -> Tue , EEEE -> Tuesday
DDay in yr(1-365,1-364)Number D -> 65 , DDD -> 065
FDay of week in month (1-5)|Number F -> 1
wWeek in year (1-53)Number w -> 7   
aAM/PMText a -> AM , aa -> AM
zTime zoneText z -> EST , zzz -> EST , zzzz -> Eastern Standard Time


Some sample of date format


 String DATE_FORMAT_1 = "dd-MMM-yyyy kk:mm";
 String DATE_FORMAT_2 = "yyyy-MM-dd HH:mm:ss";
 String DATE_FORMAT_3 = "yyyy-MM-dd";
 String DATE_FORMAT_4 = "dd-MMM-yyyy"; 
 String DATE_FORMAT_5 = "dd_MM_yyyy"; 
 String DATE_FORMAT_6 = "yyyy-MM-dd'T'HH:mm:ss"; 
 String DATE_FORMAT_7 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"; 



1. Get today date.


Example - 1
public String getCurrentTimeStr() { return new SimpleDateFormat(DATE_FORMAT_1, Locale.US).format(new Date()) }


2. Compare dates.


Example - 2
public boolean isFutureDate(String originalDate) { boolean isFuture = false; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_1, Locale.US); Date dateObj; try { dateObj = sdf.parse(originalDate); if (new Date().before(dateObj)) { isFuture = true; } } catch (ParseException e) { } return isFuture }


3. Convert UTC to Local date UTC is the common time standard across the world.


Example - 3
public String convertUtcToLocal(String dateTime) { String do = ""; if(dateTime !=null){ DateFormat originalFormat = new SimpleDateFormat(DATE_FORMAT_2, Locale.US); originalFormat.setTimeZone(TimeZone.getTimeZone("UTC")); DateFormat targetFormat = new SimpleDateFormat(DATE_FORMAT_2, Locale.US); targetFormat.setTimeZone(TimeZone.getDefault()) try { Date date = originalFormat.parse(dateTime); dob = targetFormat.format(date); } catch (ParseException e) { } } return do; }



4. Merge Date and time

private static final String DATE_TIME = "d MMM yyyy HH:mm";


Example - 4
public Date getTrainStartTime(String originalDate, String time) { String mAlertDateTime = originalDate + " " + time; SimpleDateFormat dft = new SimpleDateFormat(DATE_TIME, Locale.getDefault()); try { Date d = dft.parse(mAlertDateTime); return d; } catch (ParseException e) { e.printStackTrace(); } return new Date(); }




Share:

Youtube

We're Social

Flutter - How to develop and distribute iOS apps without Mac

As we know, we can use Flutter framework to develop desktop, web, Android and iOS apps on window OS. But we can't run and test Flutter i...