Share Coding

Tutorials, Problems, Stuffs …

Tag Archives: timestamp

[joda time] Convert timestamp into “Posted 3 minutes ago”

DateTimeZone.setDefault(DateTimeZone.UTC);
DateTime myBirthDate = new DateTime(comment.getTime()*1000);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
Log.d("period",period.toString());

PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
if(period.getYears() != 0) {
	builder.appendYears().appendSuffix(" years ago\n");
} else if(period.getMonths() != 0) {
	builder.appendMonths().appendSuffix(" months ago\n");
} else if(period.getDays() != 0) {
	builder.appendDays().appendSuffix(" days ago\n");
} else if(period.getHours() != 0) {
	builder.appendHours().appendSuffix(" hours ago\n");
} else if(period.getMinutes() != 0) {
	builder.appendMinutes().appendSuffix(" minutes ago\n");
} else if(period.getSeconds() != 0) {
	builder.appendSeconds().appendSuffix(" seconds ago\n");
}
PeriodFormatter formatter = builder.printZeroNever().toFormatter();
String elapsed = formatter.print(period);

TextView txtComment_time = (TextView) comment_list_item.findViewById(R.id.txtComment_time);
txtComment_time.setText(elapsed);

Get local time and unix time by using NSDate and NSTimeZone on IOS

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate = [dateFormatter dateFromString:@"2012-02-18 00:00:00"];
NSLog(@"%@", startDate);

The result is :
2012-02-17 16:00:00 +0000

 
We can see the time is not correct since the default timezone of NSDate is GMT +000(London), we must get the systemTimeZone and add interval to the date:

NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:startDate];
startDate = [startDate addTimeInterval:interval];
NSLog(@"%@", startDate);

The result is :
2012-02-18 00:00:00 +0000

 
Read more of this post