java常用的一些工具类
日期工具类
Date工具类封装
package Dao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Dateutils {
public static final SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd");
public static java.util.Date strtoutildate(String str){
try {
Date date = sdf.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static java.sql.Date utiltosqldate(java.util.Date date){
return new java.sql.Date(date.getTime());
}
public static String utildatetostr(java.util.Date date){
String format = sdf.format(date);
return format;
}
}
MD5加密工具类
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5utils {
/**
* 密码加密
*/
public static String encrypt(String password) throws NoSuchAlgorithmException {
//获得MD5加密对象
MessageDigest md5=MessageDigest.getInstance("md5");
//对原密码加密
md5.update(password.getBytes());
//获得加密后的密码字节
byte[] digest = md5.digest();
//将字节转化为密码字符串
StringBuilder builder = new StringBuilder();
for(byte b: digest)
{
//转化为16进制字符串
//将高4位转换为16进制
builder.append(Integer.toHexString(b>>4&0xf));
//将低4位转换为16进制
builder.append(Integer.toHexString(b&0xf));
}
return builder.toString();
}
}
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String getMD5(String password) {
try {
// 得到一个信息摘要器
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] result = digest.digest(password.getBytes());
StringBuffer buffer = new StringBuffer();
// 把每一个byte 做一个与运算 0xff;
for (byte b : result) {
// 与运算
int number = b & 0xff;// 加盐
String str = Integer.toHexString(number);
if (str.length() == 1) {
buffer.append("0");
}
buffer.append(str);
}
// 标准的md5加密后的结果
return buffer.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
}
DBUtils工具类
package com.blb.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtils {
private static Connection conn = null;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=UTF-8", "root", "root");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
/**
* 执行查询
* @param sql
* @param params
* @return
* @throws SQLException
*/
public static ResultSet executeQuery(String sql, String... params) throws SQLException{
return getParams(sql, params).executeQuery();
}
/**
* 执行添加、删除、修改
* @param sql
* @param params
* @throws SQLException
*/
public static void execute(String sql, String... params) throws SQLException{
getParams(sql, params).executeUpdate();
}
/**
* 参数处理
* @param sql
* @param params
* @return
* @throws SQLException
*/
private static PreparedStatement getParams(String sql, String... params) throws SQLException{
PreparedStatement prepareStatement = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
prepareStatement.setObject(i+1, params[i]);
}
return prepareStatement;
}
}
对事务封装的DButis
package account;
import JDBC.DBUtils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DButils {
private static final Properties PROPERTIES=new Properties();
private static final ThreadLocal<Connection> THREAD_LOCAL=new ThreadLocal<>();
static {
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
try {
PROPERTIES.load(is);
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getconnection(){
Connection conn=THREAD_LOCAL.get();//获取线程中存储的connection对象
try {
if(conn==null){//如果连接对象为空则创建连接
conn= DriverManager.getConnection(PROPERTIES.getProperty("url"),PROPERTIES.getProperty("username"),PROPERTIES.getProperty("password"));
THREAD_LOCAL.set(conn);//把连接存在当前线程共享中
}
return conn;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
//事务的开启
public static void begin()
{
Connection conn=null;
try {
conn=getconnection();
conn.setAutoCommit(false);
}catch (SQLException e)
{
e.printStackTrace();
}
}
//提交事务
public static void commit()
{
Connection conn=null;
try {
conn=getconnection();
conn.commit();
}catch (SQLException e)
{
e.printStackTrace();
}finally {
DBUtils.closeall(conn,null,null);
}
}
//回滚事务
public static void rollback()
{
Connection conn=null;
try {
conn=getconnection();
conn.rollback();
}catch (SQLException e)
{
e.printStackTrace();
}finally {
DBUtils.closeall(conn,null,null);
}
}
public static void closeall(Connection conn, PreparedStatement pst, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
THREAD_LOCAL.remove();//关闭连接后移除已关闭的connection对象
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
DaoUtils
package com.blb.utils;
import com.blb.advanced.RowMapper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Daoutils<T>{
/**
* 公共处理增删改的方法
* @param sql 执行的sql语句
* @param args 参数列表
* @return
*/
public int commonsUpdate(String sql,Object...args){
Connection conn=null;
PreparedStatement pst=null;
conn = DButils.getConnection();
try {
pst=conn.prepareStatement(sql);
for(int i=0;i<args.length;i++){
pst.setObject(i+1,args[i]);
}
int i = pst.executeUpdate();
return i;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DButils.closeall(null,pst,null);
}
return 0;
}
public List<T> commonsSelect(String sql, RowMapper<T> rowMapper,Object...args)
{
List<T> arr=new ArrayList<>();
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
try {
conn=DButils.getConnection();
pst=conn.prepareStatement(sql);
if(args!=null){//注意要判断非空否则查询所有的时候会报错误
for(int i=0;i<args.length;i++)
{
pst.setObject(i+1,args[i]);
}
}
rs = pst.executeQuery();
while (rs.next()){
//根据查询到的结果完成orm
T t=rowMapper.getRow(rs);
arr.add(t);
}
return arr;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DButils.closeall(null,pst,rs);
}
return null;
}
}
在建一个包用于实现查询里面的orm映射,并且使用泛型这样可以供所有的使用
RowMapper 接口
package com.blb.advanced;
import java.sql.ResultSet;
public interface RowMapper<T> {
public T getRow(ResultSet rs);
}
PersonRowMapper 实现类
package com.blb.advanced.Impl;
import com.blb.advanced.RowMapper;
import com.blb.entity.Person;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PersonRowMapper implements RowMapper<Person> {
@Override
public Person getRow(ResultSet rs) {
Person person=null;
int id1 = 0;
try {
id1 = rs.getInt("id");
int age = rs.getInt("age");
String name = rs.getString("name");
String email = rs.getString("email");
String address = rs.getString("address");
Date date = rs.getDate("borndate");
person=new Person(id1,name,age,date,email,address);
return person;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
Druid DButils
package com.blb.utils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DButils {
//声明连接池对象
private static DruidDataSource ds;
private static final ThreadLocal<Connection> THREAD_LOCAL=new ThreadLocal<>();
static {
//实例化配置对象
Properties properties=new Properties();
InputStream inputStream= DButils.class.getResourceAsStream("/db.properties");
try {
properties.load(inputStream);
ds=(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接对象
public static Connection getConnection()
{
Connection conn=THREAD_LOCAL.get();
try {
if(conn == null){
conn=ds.getConnection();
THREAD_LOCAL.set(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void begin(){
Connection conn=null;
try {
conn=getConnection();
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void commit(){
Connection conn=null;
try {
conn=getConnection();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}finally {
closall(conn,null,null);
}
}
public static void rollback()
{
Connection conn=null;
try {
conn=getConnection();
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}finally {
closall(conn,null,null);
}
}
public static void closall(Connection conn, PreparedStatement pst, ResultSet rs){
try {
if(rs!=null){
rs.close();
if(pst!=null){
pst.close();
}
if(conn!=null){
conn.close();
THREAD_LOCAL.remove();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//返回一个数据源
public static DataSource getDataSource(){
return ds;
}
}
生成验证码
需要 ValidateCode.jar包
页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<form action="login" method="post">
用户名:<input type="text" name="username" /><br>
密码:<input type="password" name="password" /><br>
验证码:<input type="text" name="vcode" /><img src="/servlet01_war_exploded/createcode"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
生成验证码
package com.blb.demo;
import cn.dsna.util.images.ValidateCode;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/createcode")
public class CreateCode extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ValidateCode vc=new ValidateCode(100,50,4,10);
//获得生成验证码里的内容
String code = vc.getCode();
HttpSession session = request.getSession();
session.setAttribute("code",code);
//响应给客户端
vc.write(response.getOutputStream());
}
}
生成ValidateCode对象的四个参数分别是:宽,高,字符个数,划线的个数
VerifyCodeUtils
package com.blb.emp.utils;
import org.apache.log4j.Logger;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.imageio.ImageIO;
public class VerifyCodeUtils {
private static final Logger logger = Logger.getLogger(VerifyCodeUtils.class);
private VerifyCodeUtils() {
}
public static final String VERIFY_CODES = "0123456789";
private static SecureRandom random = new SecureRandom();
/**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources){
String _sources = sources;
if(_sources == null || _sources.length() == 0){
_sources = VERIFY_CODES;
}
int codesLen = _sources.length();
SecureRandom rand = new SecureRandom();
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(_sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 输出随机验证码图片流,并返回验证码值
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
FileOutputStream fos = null;
try{
outputFile.createNewFile();
fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
} catch(IOException e){
logger.error("生成指定验证码图像文件", e);
} finally {
try {
fos.close();
} catch (IOException e) {
logger.error("生成指定验证码图像文件", e);
}
}
}
/**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
SecureRandom rand = new SecureRandom();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h-4);
//绘制干扰线
SecureRandom random = new SecureRandom();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
int _fc = fc;
int _bc = bc;
if (_fc > 255)
{
_fc = 255;
}
if (_bc > 255)
{
_bc = 255;
}
int r = _fc + random.nextInt(_bc - _fc);
int g = _fc + random.nextInt(_bc - _fc);
int b = _fc + random.nextInt(_bc - _fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
controller
package com.blb.emp.controller;
import com.blb.emp.utils.VerifyCodeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller
@RequestMapping("user")
public class UserController {
/**
* 用来生成验证码方法
*/
@RequestMapping("/generateImageCode")
public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
//1.生成随机字符串
String code= VerifyCodeUtils.generateVerifyCode(4);
//2.保存随机字符串到session中
session.setAttribute("code",code);
//3.将随机字符串生成图片
//4.response响应图片
response.setContentType("image/png");//指定响应类型
ServletOutputStream outputStream = response.getOutputStream();
VerifyCodeUtils.outputImage(220,80,outputStream,code);
}
}
package com.blb.msbd.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 日期操作工具类
*/
public class DateUtils {
/**
* 日期转换- String -> Date
*
* @param dateString 字符串时间
* @return Date类型信息
* @throws Exception 抛出异常
*/
public static Date parseString2Date(String dateString) throws ParseException {
if (dateString == null) {
return null;
}
return parseString2Date(dateString, "yyyy-MM-dd");
}
/**
* 日期转换- String -> Date
*
* @param dateString 字符串时间
* @param pattern 格式模板
* @return Date类型信息
* @throws Exception 抛出异常
*/
public static Date parseString2Date(String dateString, String pattern) throws ParseException {
if (dateString == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = sdf.parse(dateString);
return date;
}
/**
* 日期转换 Date -> String
* @param date Date类型信息
* @return 字符串时间
* @throws Exception 抛出异常
*/
public static String parseDate2String(Date date) {
if (date == null) {
return null;
}
return parseDate2String(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 日期转换 Date -> String
*
* @param date Date类型信息
* @param pattern 格式模板
* @return 字符串时间
* @throws Exception 抛出异常
*/
public static String parseDate2String(Date date, String pattern){
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String strDate = sdf.format(date);
return strDate;
}
/**
* 获取当前日期的本周一是几号
*
* @return 本周一的日期
*/
public static Date getThisWeekMonday() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
// 获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
return cal.getTime();
}
/**
* 获取当前日期周的最后一天
*
* @return 当前日期周的最后一天
*/
public static Date getSundayOfThisWeek() {
Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek == 0) {
dayOfWeek = 7;
}
c.add(Calendar.DATE, -dayOfWeek + 7);
return c.getTime();
}
/**
* 根据日期区间获取月份列表
*
* @param minDate 开始时间
* @param maxDate 结束时间
* @return 月份列表
* @throws Exception
*/
public static List<String> getMonthBetween(String minDate, String maxDate, String format) throws ParseException{
ArrayList<String> result = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
min.setTime(sdf.parse(minDate));
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(sdf.parse(maxDate));
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
SimpleDateFormat sdf2 = new SimpleDateFormat(format);
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf2.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);
}
return result;
}
/**
* 根据日期获取年度中的周索引
*
* @param date 日期
* @return 周索引
* @throws Exception
*/
public static Integer getWeekOfYear(String date) throws ParseException {
Date useDate = parseString2Date(date);
Calendar cal = Calendar.getInstance();
cal.setTime(useDate);
return cal.get(Calendar.WEEK_OF_YEAR);
}
/**
* 根据年份获取年中周列表
*
* @param year 年分
* @return 周列表
* @throws Exception
*/
public static Map<Integer, String> getWeeksOfYear(String year) throws ParseException {
Date useDate = parseString2Date(year, "yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(useDate);
//获取年中周数量
int weeksCount = cal.getWeeksInWeekYear();
Map<Integer, String> mapWeeks = new HashMap<>(55);
for (int i = 0; i < weeksCount; i++) {
cal.get(Calendar.DAY_OF_YEAR);
mapWeeks.put(i + 1, parseDate2String(getFirstDayOfWeek(cal.get(Calendar.YEAR), i)));
}
return mapWeeks;
}
/**
* 获取某年的第几周的开始日期
*
* @param year 年分
* @param week 周索引
* @return 开始日期
* @throws Exception
*/
public static Date getFirstDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getFirstDayOfWeek(cal.getTime());
}
/**
* 获取某年的第几周的结束日期
*
* @param year 年份
* @param week 周索引
* @return 结束日期
* @throws Exception
*/
public static Date getLastDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
return getLastDayOfWeek(cal.getTime());
}
/**
* 获取当前时间所在周的开始日期
*
* @param date 当前时间
* @return 开始时间
*/
public static Date getFirstDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.SUNDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
return c.getTime();
}
/**
* 获取当前时间所在周的结束日期
*
* @param date 当前时间
* @return 结束日期
*/
public static Date getLastDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.SUNDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
return c.getTime();
}
//获得上周一的日期
public static Date geLastWeekMonday(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(getThisWeekMonday(date));
cal.add(Calendar.DATE, -7);
return cal.getTime();
}
//获得本周一的日期
public static Date getThisWeekMonday(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// 获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 获得当前日期是一个星期的第几天
int day = cal.get(Calendar.DAY_OF_WEEK);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
return cal.getTime();
}
//获得下周一的日期
public static Date getNextWeekMonday(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(getThisWeekMonday(date));
cal.add(Calendar.DATE, 7);
return cal.getTime();
}
//获得今天日期
public static Date getToday(){
return new Date();
}
//获得本月一日的日期
public static Date getFirstDay4ThisMonth(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH,1);
return calendar.getTime();
}
public static void main(String[] args) {
try {
System.out.println("本周一" + parseDate2String(getThisWeekMonday()));
System.out.println("本月一日" + parseDate2String(getFirstDay4ThisMonth()));
} catch (Exception e) {
e.printStackTrace();
}
}
}