当先锋百科网

首页 1 2 3 4 5 6 7

可以根据当前时间计算出距离某个时间点是几分钟前,还是几小时前,几天前

纯java实现的:几秒前,几分钟前,几小时前,几天前,几月前,几年前的实现 http://www.zuidaima.com/share/1562038902000640.htm

原文:http://www.zuidaima.com/share/1550463224564736.htm

1.[代码]java实现几分钟前,几小时前,几天前的代码

package com.zuidaima.test;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

import org.junit.Test;

import org.ocpsoft.pretty.time.PrettyTime;

public class Main {

@Test

public void testLocal() {

PrettyTime p = new PrettyTime(new Locale("ZH_CN"));

System.out.println(p.format(new Date()));

}

@Test

public void testMinutesFromNow() throws Exception {

PrettyTime t = new PrettyTime(new Date(0));

System.out.println(t.format(new Date(1000 * 60 * 12)));

}

@Test

public void testMomentsAgo() throws Exception {

PrettyTime t = new PrettyTime(new Date(6000));

System.out.println(t.format(new Date(0)));

}

@Test

public void testMinutesAgo() throws Exception {

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:m:s");

Date date = format.parse("2012-07-18 23:42:05");

Date now = new Date();

PrettyTime t = new PrettyTime(now);

System.out.println(t.format(date));

}

}