我正在添加这个问题,因为我是Java和Android的新手,我搜索了几个小时试图解决这个问题.答案来自相关答案的组合,所以我想我会记录我为其他可能正在努力的人学到的东西.见答案.
对于一些背景知识,我的经验主要是PHP的Web开发和一点Ruby.我唯一的操作系统是Linux(Ubuntu Studio),我(不情愿地)在Android Studio 2.1.2中开发我的第一个Android应用程序.我的Java设置如下:
>java -version
> openjdk version "1.8.0_91"
> OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-3ubuntu1~15.10.1-b14)
> OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
Run Code Online (Sandbox Code Playgroud) datetime android android-gradle-plugin threetenbp threetenabp
我是Java新手,通常使用PHP.
我想转换这个字符串:
2011年3月14日星期四16:02:37 GMT
进入一个Calendar对象,这样我就可以像这样轻松地拉出Year和Month:
String yearAndMonth = cal.get(Calendar.YEAR)+cal.get(Calendar.MONTH);
Run Code Online (Sandbox Code Playgroud)
手动解析是不是一个坏主意?使用子字符串方法?
任何建议都会有所帮助!
我想在Java中使用这种格式解析String的最佳方法是dd/MM/yyyy [到dd/MM/yyyy].带[]的字符串是可选的,dd代表日期的2位数表示,MM是月份的2位数表示,yyyy是年份的4位数表示.
更新
谢谢大家的快速响应,但是我忘了告诉你[]是象征可选的,字符串中没有[]示例字符串可能是
目前我用这种方式编写代码,工作但很难看=(
String _daterange = (String) request.getParameter("daterange");
Date startDate = null, endDate = null;
// Format of incoming dateRange is
if (InputValidator.requiredValidator(_daterange)) {
String[] _dateRanges = _daterange.toUpperCase().split("TO");
try {
startDate = (_dateRanges.length > 0) ? sdf.parse(_dateRanges[0]) : null;
try{
endDate = (_dateRanges.length > 1) ? sdf.parse(_dateRanges[1]) : null;
}catch(Exception e){
endDate = null;
}
} catch (Exception e) {
startDate = null;
}
}
Run Code Online (Sandbox Code Playgroud) 我想获取具有给定日期的当前星期,例如,如果日期为2016/01/19,则结果为:week number: 3
我已经看到了一些有关此的问题和答案,但是我无法实现我想要的。这是我所做的:
public static int getCurrentWeek() {
String input = "20160115";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
return week;
}
Run Code Online (Sandbox Code Playgroud)
我从这个问题中获取了这段代码,但是在这一行上有一个错误:
Date date = df.parse(input);
Run Code Online (Sandbox Code Playgroud)
未处理的异常类型ParseException
java ×3
date ×2
datetime ×2
android ×1
calendar ×1
regex ×1
string ×1
threetenabp ×1
threetenbp ×1