在Java中生成两个给定日期之间的所有日期
我试图获取一个日期数组,而我的输入是一个“from”/“to”结构。 因此,我的意见是:在Java中生成两个给定日期之间的所有日期,java,date,simpledateformat,timeunit,Java,Date,Simpledateformat,Timeunit,我试图获取一个日期数组,而我的输入是一个“from”/“to”结构。 因此,我的意见是: String date1 = "2014-01-01"; String date2 = "2014-05-01"; 我的输出应该是一个所有日期都在date1和date2之间的Arraylist。 我已经找过了,但我只能找到关于两次约会之间差异的问题: SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy"); String inputSt
String date1 = "2014-01-01";
String date2 = "2014-05-01";
我的输出应该是一个所有日期都在date1和date2之间的Arraylist。
我已经找过了,但我只能找到关于两次约会之间差异的问题:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff,TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
有什么提示或建议吗?所有其他问题都是针对iOS或SQL的。看看JodaTime:
DateTime dateTime1=新的日期时间(date1);
DateTime dateTime2=新的日期时间(date2);
List allDates=new ArrayList();
while(dateTime1.before(dateTime2)){
add(dateTime1.toDate());
dateTime1=dateTime1.plusDays(1);
}
如果您不想使用第三方库,可以使用日历
:
检查
publicstaticvoidmain(字符串[]args)引发异常{
SimpleDataFormat myFormat=新的SimpleDataFormat(“dd-MM-yyyy”);
字符串inputString1=“23 01 1997”;
字符串inputString2=“27 04 1997”;
ArrayList日期=新建ArrayList();
试一试{
Date date1=myFormat.parse(inputString1);
日历c1=DateToCalendar(日期1);
Date date2=myFormat.parse(inputString2);
日历c2=DateToCalendar(日期2);
而(!Areequalate(c1,c2)){
dates.add(c1.getTime());
System.out.println(c1.getTime());
c1.添加(日历日/年,1);
}
}捕获(解析异常){
e、 printStackTrace();
}
//ArrayList dates>>包含两个给定日期之间的所有日期。
}
专用静态布尔值areEqualDate(日历c1、日历c2){
如果(c1.get(日历年)!=c2.get(日历年))返回false;
如果(c1.get(Calendar.MONTH)!=c2.get(Calendar.MONTH))返回false;
如果(c1.get(日历年的日历日)!=c2.get(日历年的日历日))返回false;
返回true;
}
公共静态日历DateToCalendar(日期){
Calendar cal=Calendar.getInstance();
校准设定时间(日期);
返回cal;
}
我喜欢JodaTime,但也可以使用java.util.Calendar
在没有第三方库的情况下完成。给定一个Calendar
对象,可以使用它的add
方法来增加日期的某些字段,同时遵守日历规则(例如,将1天添加到1月31日将使您到达2月1日,而不是1月32日)
首先,将日期按正确的时间顺序放入一个日历对象中,以便以后添加的方向正确:
Calendar cStart = Calendar.getInstance(),
cStop = Calendar.getInstance();
if (date1.before(date2)) {
cStart.setTime(date1);
cStop.setTime(date2);
} else {
cStart.setTime(date2);
cStop.setTime(date1);
为了简单起见,date1
和date2
是您问题中解析的Date
对象
接下来,循环一条“将1添加到一年中的某一天”指令,直到您超过停止日期:
do {
System.out.println(pretty(cStart));
cStart.add(Calendar.DAY_OF_YEAR, 1);
} while (cStart.before(cStop));
最后打印停止日期
System.out.println(pretty(cStop));
pretty()
此解决方案将打印日期范围,包括开始和停止日期,并且可能需要围绕边缘情况进行一些调整(例如date1==date2
)。可以轻松调整以排除开始和停止日期。当然,打印可以替换为聚合。要从日历中获取日期对象,请使用getTime()
方法(返回快照,而不是实时引用)
可以找到相关的(格里高利)日历的文档。我已经知道OP没有使用Java 8,但这里是当前的解决方案-Java已经过改进,新的Java。time
API在这方面做了所有可以想象的工作:
//change these values :
LocalDate ld1 = LocalDate.ofEpochDay(0);
LocalDate ld2 = LocalDate.now();
//do NOT change these:
final LocalDate begin = ld1.isBefore(ld2) ? ld1 : ld2;
final LocalDate end = ld2.isAfter(ld1) ? ld2 : ld1;
for (int i = 0; i < begin.until(end, ChronoUnit.DAYS); i++) {
final LocalDate curDate = begin.plusDays(i);
System.out.println("current date : " + curDate);
}
//更改这些值:
LocalDate ld1=LocalDate.ofEpochDay(0);
LocalDate ld2=LocalDate.now();
//请勿更改以下内容:
最终LocalDate begin=ld1.isBefore(ld2)?ld1:ld2;
最终LocalDate end=ld2.isAfter(ld1)?ld2:ld1;
for(int i=0;i
这将在两个日期之间每隔有效的天输出一次,而大多数其他解决方案也会给出无效的解决方案;事情是这样的:时间计算需要在与时区无关的数据上进行-另一方面,输出很可能与时区和/或年代有关。
这就是为什么会有像java.time.format
这样的软件包-只需计算您的时间/日期值,然后为您选择的区域格式化它们。。。这就是正确的做法
如果您需要转换时态输入,time API中还有一些有用的函数,我建议您就这一主题做一个全面的教程,可能会有一些很好的介绍,尤其是:
有两种表示时间的基本方法。一种方式代表时间
人工术语,称为人工时间,例如年、月、日,
小时,分,秒。另一种方式,机器时间,测量时间
从一个称为“纪元”的原点沿时间线连续移动,以
纳秒分辨率。日期时间包提供了丰富的
用于表示日期和时间的类。日期时间中的一些类
API旨在表示机器时间,而其他API则更适合
代表人类时间
下面是获取两个字符串日期之间日期数组的代码
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class DateFormatExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String date1 = "2014-01-01";
String date2 = "2014-05-01";
try {
Date d1 = myFormat.parse(date1);
Date d2 = myFormat.parse(date2);
List<Date> allDates = new ArrayList<Date>();
List<String> allDatesString = new ArrayList<String>();
while( d1.before(d2) ){
d1 = addDays(d1, 1);
allDates.add(d1);
allDatesString.add(formatter.format(d1));
}
System.out.println(allDates);
System.out.println(allDatesString);
} catch (ParseException e) {
e.printStackTrace();
}
}
private static Date addDays(Date d1, int i) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d1);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
}
import java.text.ParseException;
导入java.text.simpleDataFormat;
导入java.util.ArrayList;
导入java.util.Calendar;
导入java.util.Date;
导入java.util.GregorianCalendar;
导入java.util.List;
公共类DateFormatExample{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
SimpleDataFormat myFormat=新SimpleDataFormat(“yyyy-MM-dd”);
SimpleDataFormat格式化程序=新的SimpleDataFormat(“yyyy-MM-dd”);
字符串date1=“2014-01-01”;
字符串date2=“2014-05-01”;
//change these values :
LocalDate ld1 = LocalDate.ofEpochDay(0);
LocalDate ld2 = LocalDate.now();
//do NOT change these:
final LocalDate begin = ld1.isBefore(ld2) ? ld1 : ld2;
final LocalDate end = ld2.isAfter(ld1) ? ld2 : ld1;
for (int i = 0; i < begin.until(end, ChronoUnit.DAYS); i++) {
final LocalDate curDate = begin.plusDays(i);
System.out.println("current date : " + curDate);
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class DateFormatExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String date1 = "2014-01-01";
String date2 = "2014-05-01";
try {
Date d1 = myFormat.parse(date1);
Date d2 = myFormat.parse(date2);
List<Date> allDates = new ArrayList<Date>();
List<String> allDatesString = new ArrayList<String>();
while( d1.before(d2) ){
d1 = addDays(d1, 1);
allDates.add(d1);
allDatesString.add(formatter.format(d1));
}
System.out.println(allDates);
System.out.println(allDatesString);
} catch (ParseException e) {
e.printStackTrace();
}
}
private static Date addDays(Date d1, int i) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d1);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
}
LocalDate start = LocalDate.parse("2015-01-01");
LocalDate end = LocalDate.parse("2019-02-01");
Range<LocalDate> range = Range.closed(start, end); //Creates a "closed" range, that is both dates are inclusive. There are also options like "openClosed", "closedOpen" and "open"
final Set<LocalDate> daySet = ContiguousSet.create(range, LocalDateDomain.INSTANCE); //Create a "virtual" set of days in given the range. "virtual" part means that if you create a set of 10 thousand years, it will not eat your memory at all
for (LocalDate day : daySet) {
//...operation...
}
public class LocalDateDomain extends DiscreteDomain<LocalDate> {
public static final LocalDateDomain INSTANCE = new LocalDateDomain();
@Override
public LocalDate next(LocalDate value) {
return value.plusDays(1);
}
@Override
public LocalDate previous(LocalDate value) {
return value.minusDays(1);
}
@Override
public long distance(LocalDate start, LocalDate end) {
return Days.daysBetween(start, end).getDays();
}
}