我在工作中支持一个公共库,它对给定字符串执行许多检查,以查看它是否是有效日期.Java API,commons-lang库和JodaTime都有方法可以解析字符串并将其转换为日期,让你知道它是否真的是一个有效的日期,但我希望有一种方法在没有实际创建日期对象的情况下进行验证(或者像JodaTime库那样使用DateTime).例如,这是一段简单的示例代码:
public boolean isValidDate(String dateString) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
try {
df.parse(dateString);
return true;
} catch (ParseException e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很浪费,我们扔掉了最终的对象.从我的基准测试中,我们在这个公共图书馆中有大约5%的时间用于验证日期.我希望我只是错过了一个明显的API.任何建议都会很棒!
UPDATE
假设我们始终可以使用相同的日期格式(可能是yyyyMMdd).我确实考虑过使用正则表达式,但是它需要知道每个月的天数,闰年等等......
结果
解析了一千万次的约会
Using Java's SimpleDateFormat: ~32 seconds
Using commons-lang DateUtils.parseDate: ~32 seconds
Using JodaTime's DateTimeFormatter: ~3.5 seconds
Using the pure code/math solution by Slanec: ~0.8 seconds
Using precomputed results by Slanec and dfb (minus filling cache): ~0.2 seconds
Run Code Online (Sandbox Code Playgroud)
有一些非常有创意的答案,我很感激!我想现在我只需要决定我需要多少灵活性,我希望代码看起来像.我要说dfb的答案是正确的,因为它纯粹是最快的,这是我原来的问题.谢谢!
我使用C制作了一个程序来查找输入的年份是否是闰年.但遗憾的是它运作不佳.它说一年是飞跃,前一年不是飞跃.
#include<stdio.h>
#include<conio.h>
int yearr(int year);
void main(void)
{
int year;
printf("Enter a year:");
scanf("%d",&year);
if(!yearr(year))
{
printf("It is a leap year.");
}
else
{
printf("It is not a leap year");
}
getch();
}
int yearr(int year)
{
if((year%4==0)&&(year/4!=0))
return 1;
else
return 0;
}
Run Code Online (Sandbox Code Playgroud)
阅读评论后,我编辑了我的编码:
#include<stdio.h>
#include<conio.h>
int yearr(int year);
void main(void)
{
int year;
printf("Enter a year:");
scanf("%d",&year);
if(!yearr(year))
{
printf("It is a leap year.");
}
else
{
printf("It is not a leap year");
}
getch();
}
int …Run Code Online (Sandbox Code Playgroud) 可能重复:
用于计算闰年的Java代码,此代码是否正确?
这是作业,我已经收到了我的成绩,但我没有在我的代码中实现闰年.这是一个简单的程序,可根据用户输入显示一个月内的数字.唯一的问题是我无法弄清楚实现闰年的方法是在2月而不是28天获得29天,而不需要写多个if语句.当然有一种更简单的方法吗?这是代码:
//Displays number of days in a month
package chapter_3;
import java.util.Scanner;
public class Chapter_3 {
public static void main(String[] args) {
System.out.println("This program will calculate \n"
+ "the number of days in a month based upon \n"
+ "your input, when prompted please enter \n"
+ "the numerical value of the month you would like\n"
+ "to view including the year. Example: if you would like\n"
+ "to view March enter 3 2011 and so …Run Code Online (Sandbox Code Playgroud) 我在Eclipse中使用Java编写了这个程序.
我能够利用我发现的公式,我在注释部分解释过.
使用for循环我可以遍历一年中的每个月,我在该代码中感觉很好,对我来说似乎干净顺利.也许我可以给变量全名以使一切更具可读性但我只是在其基本本质中使用公式:)
好吧,我的问题是它没有像2008年那样正确计算......闰年.
我知道如果(年%400 == 0 ||(年%4 == 0 &&年%100!= 0))那么我们有一个闰年.
也许如果这一年是闰年,我需要从某个月减去一定的天数.
任何解决方案,或某些方向将是非常感谢:)
package exercises;
public class E28 {
/*
* Display the first days of each month
* Enter the year
* Enter first day of the year
*
* h = (q + (26 * (m + 1)) / 10 + k + k/4 + j/4 + 5j) % 7
*
* h is the day of the week (0: Saturday, 1: Sunday ......)
* q is …Run Code Online (Sandbox Code Playgroud)