Java 如何将当前时间与时间范围进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6377278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare current time with time range?
提问by LA_
I have two String variables - time1
and time2
. Both contain value in the format HH:MM. How can I check:
我有两个字符串变量 -time1
和time2
. 两者都包含格式为HH:MM 的值。我如何检查:
- If the current time is within
time1
andtime2?
time1
will happen in the nearest hour?
- 如果当前时间在
time1
和time2?
time1
会在最近的一个小时内发生吗?
Upd.I've implemented the following to convert time1
to Date
format. But it uses depreciated methods:
更新。我已经实现了以下转换time1
为Date
格式。但它使用折旧方法:
Date clTime1 = new Date();
SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
try {
clTime1 = timeParser.parse(time1);
} catch (ParseException e) {
}
Calendar now = Calendar.getInstance();
clTime1.setYear(now.get(Calendar.YEAR) - 1900);
clTime1.setMonth(now.get(Calendar.MONTH));
clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
System.out.println(clTime1.toString());
采纳答案by Caspar Harmer
- Convert the two strings to
Date
objects (which are also time objects) Create a newDate
object. - This will contain the current time.
- Use the Date.before() and Date.after() methods to determine if you are in the time interval.
- 将两个字符串转换为
Date
对象(也是时间对象) 创建一个新Date
对象。 - 这将包含当前时间。
- 使用 Date.before() 和 Date.after() 方法来确定您是否在时间间隔内。
EDIT: You should be able to use this directly (and no deprecated methods)
编辑:您应该能够直接使用它(并且没有不推荐使用的方法)
public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
//yada yada
}
}
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
回答by DArkO
Look into the Calendar class. It has the methods to support what you are asking. Date is deprecated and not recommended to use.
查看 Calendar 类。它具有支持您所要求的方法的方法。不推荐使用日期,不推荐使用。
Here is the link to the API. Calendar
这是 API 的链接。日历
About the usage. First you need to call Calendar.getInstance()
to create a calendar object.
Next you need to Set the two fields using cal.set(Calendar.HOUR, your hours)
and Calendar.MINUTES
the same way. Next you can call the compare function, before or after functions to get the desired info. Also you can get an instance with the current time in the current locale.
关于用法。首先,您需要调用Calendar.getInstance()
以创建日历对象。接下来,您需要使用cal.set(Calendar.HOUR, your hours)
和Calendar.MINUTES
相同的方式设置两个字段。接下来,您可以在函数之前或之后调用比较函数来获取所需的信息。您还可以在当前语言环境中获取具有当前时间的实例。
回答by LA_
As of now, I am thinking about the following approach:
截至目前,我正在考虑以下方法:
int clTime = Integer.parseInt(time1.substring(0, 1))*60 + Integer.parseInt(time1.substring(3, 4));
Time now = new Time();
now.setToNow();
int nowTime = now.hour*60 + now.minute;
So, I'll need to compare just integer values clTime
and nowTime
.
所以,我只需要比较整数值clTime
和nowTime
.
回答by Osama Ibrahim
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Date EndTime = dateFormat.parse("10:00");
Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
if (CurrentTime.after(EndTime))
{
System.out.println("timeeee end ");
}
Don't forget to surrounded with a try catch block
不要忘记用 try catch 块包围
回答by Puneet Bahuguna
For example if you want to compare time between 11pm to 6am for calculating extra night fare for any vechicle. then following code will help you.
例如,如果您想比较晚上 11 点到早上 6 点之间的时间以计算任何车辆的额外夜间票价。那么下面的代码会帮助你。
// Code
// 代码
package com.example.timedate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.os.Bundle;
import android.app.Activity;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView tv;
Button bt;
int hour,min;
String AM_PM;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
bt = (Button)findViewById(R.id.button1);
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());*/
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
int ds = c.get(Calendar.AM_PM);
if(ds==0)
AM_PM="am";
else
AM_PM="pm";
Toast.makeText(MainActivity.this, ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();
if((hour==11&&AM_PM.matches("pm")) || (hour<7&&AM_PM.matches("am")) || (hour==12&&AM_PM.matches("am")))
{
Toast.makeText(MainActivity.this, "Time is between the range", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(MainActivity.this, "Time is not between the range", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}`
回答by kinsley kajiva
This is what I used as simple function and it worked for me:
这就是我使用的简单函数,它对我有用:
public static boolean isTimeWith_in_Interval(String valueToCheck, String startTime, String endTime) {
boolean isBetween = false;
try {
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(startTime);
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(endTime);
Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);
if (time1.before(d) && time2.after(d)) {
isBetween = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return isBetween;
}
回答by Praveen
Try this if you have specific time Zone.
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh a");
Date timeseven = dateFormat.parse("7 AM");
Date timeTen = dateFormat.parse("10 AM");
Date timeOne = dateFormat.parse("1 PM");
Date timefour = dateFormat.parse("4 PM");
Date timefive = dateFormat.parse("10 PM");
//Get current time
// Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
//Sample time
Date CurrentTime = dateFormat.parse("9 PM");
if (CurrentTime.after(timeseven) && CurrentTime.before(timeTen)) {
Toast.makeText(this, "FIRST", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeTen) && CurrentTime.before(timeOne)) {
Toast.makeText(this, "Secound", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timeOne) && CurrentTime.before(timefour)) {
Toast.makeText(this, "THird", Toast.LENGTH_SHORT).show();
} else if (CurrentTime.after(timefour) && CurrentTime.before(timefive)) {
Toast.makeText(this, "Fourth", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not found in your time zone", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
回答by Abhay Pratap
if you want time between after 9PM to before 9Am you can use following condition..
如果您想要在晚上 9 点之后到上午 9 点之前的时间,您可以使用以下条件..
if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
// do your stuffs
}