Java获取当前日期为当年的第几周

2023-12-25 19:06:33

controller

package com.包名.路径.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.日期格式验证.date.DateFormatValid;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Api(tags = {"模块/接口名/主要功能"})
@Slf4j
@Validated
@RestController
@RequestMapping("url路径")
public class LpgSelfWeekController {

    @ApiOperation(value = "获取第几周")
    @GetMapping("/getWeek")
    public R<Integer> getWeek(@Validated @DateFormatValid String localDate) {
        LocalDate date = LocalDate.now();
        if (StrUtil.isNotBlank(localDate)){
            DateTimeFormatter fm = DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN);
            date = LocalDate.parse(localDate, fm);
        }
        return R.ok(getWeek(date));
    }


	/**
     * 返回值为 参数当年的 第几周
     * 若参数为空 则返回当前时间 是当年的第几周
     *
     * @param date
     * @return Integer
     */
    public static Integer getWeek(LocalDate date){
        WeekFields weekFields = WeekFields.of(Locale.getDefault());
        TemporalField temporalField = weekFields.weekOfYear();

        if (ObjectUtil.isNull(date)){
            return LocalDate.now().get(temporalField);
        }else {
            return date.get(temporalField);
        }
    }
}

日期格式,进行验证

package com.日期格式验证.date;

import cn.hutool.core.date.DatePattern;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 日期格式验证
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({
        ElementType.METHOD,
        ElementType.FIELD,
        ElementType.ANNOTATION_TYPE,
        ElementType.CONSTRUCTOR,
        ElementType.PARAMETER,
        ElementType.TYPE_USE
})
@Constraint(
        validatedBy = {DateFormatValidChecker.class}
)
public @interface DateFormatValid {

    String message() default " 日期格式错误 正确为 yyyy-MM-dd";

    String value() default DatePattern.NORM_DATE_PATTERN;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}
package com.日期格式.valid.date;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description 日期格式验证   date: yyyy-MM-dd   datetime : yyyy-MM-dd HH:mm:ss
 */
public class DateFormatValidChecker implements ConstraintValidator<DateFormatValid, String> {

    private DateFormatValid dateFormatValid;

    public DateFormatValidChecker() {
    }

    public void initialize(DateFormatValid dateFormatValid) {
        this.dateFormatValid = dateFormatValid;
    }

    public boolean isValid(String date, ConstraintValidatorContext constraintValidatorContext) {
        if (StrUtil.isBlank(date)) {
            return true;
        } else {
            //清理格式
            date = date.trim();
            try {
                LocalDate.parse(date, DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
                return true;
            } catch (Exception var6) {
                return false;
            }
        }
    }

    //date 验证
    @Deprecated
    public boolean check(String str) {
        String date = "^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$";
        Pattern r = Pattern.compile(date);
        Matcher matcher = r.matcher(str);
        return matcher.find();
    }
}

R对象(这个可以用别的)

package com.包名.路径.response;

import com.gas.enums.ErrorEnums;
import com.gas.util.GasJkJsonUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.baomidou.mybatisplus.extension.api.R;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

@ApiModel(
    value = "R对象",
    description = "通用响应实体"
)
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final int SUCCESS = 200;
    public static final int ERROR;
    @ApiModelProperty("响应编码")
    private int code;
    @ApiModelProperty("响应描述信息")
    private String msg;
    @ApiModelProperty("响应内容")
    private T data;

    public static <T> R<T> success(String msg) {
        return restResult((Object)null, 200, msg);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, 200, (String)null);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, 200, msg);
    }

    public static <T> R<T> miss(String msg) {
        return restResult((Object)null, ErrorEnums.BUSINESS_ERROR.getCode(), msg);
    }

    public static <T> R<T> failed(String msg) {
        return restResult((Object)null, ERROR, msg);
    }

    public static <T> R<T> failed(ErrorEnums errorEnums) {
        return restResult((Object)null, errorEnums.getCode(), errorEnums.getMsg());
    }

    public static <T> R<T> failed(ErrorEnums errorEnums, String msg) {
        return restResult((Object)null, errorEnums.getCode(), msg);
    }

    public static <T> R<T> failed(T data, ErrorEnums errorEnums) {
        return restResult(data, errorEnums.getCode(), errorEnums.getMsg());
    }

    public static <T> R<T> failed(T data, ErrorEnums errorEnums, String msg) {
        return restResult(data, errorEnums.getCode(), msg);
    }

    public static <T> R<T> failed(int code, String msg) {
        return restResult((Object)null, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public static <T> void printJson(HttpServletResponse response, T data, int code, String msg) {
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter pw = null;

        try {
            pw = response.getWriter();
        } catch (Exception var7) {
            var7.printStackTrace();
        }

        Map<String, Object> paramsMap = new HashMap();
        paramsMap.put("data", data);
        paramsMap.put("code", code);
        paramsMap.put("msg", msg);
        String json = GasJkJsonUtil.toJsonStr(paramsMap, true);
        pw.print(json);
        pw.flush();
        pw.close();
    }

    public String toString() {
        return "R(code=" + this.getCode() + ", msg=" + this.getMsg() + ", data=" + this.getData() + ")";
    }

    public R() {
    }

    public R(final int code, final String msg, final T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public int getCode() {
        return this.code;
    }

    public R<T> setCode(final int code) {
        this.code = code;
        return this;
    }

    public String getMsg() {
        return this.msg;
    }

    public R<T> setMsg(final String msg) {
        this.msg = msg;
        return this;
    }

    public T getData() {
        return this.data;
    }

    public R<T> setData(final T data) {
        this.data = data;
        return this;
    }

    static {
        ERROR = ErrorEnums.SYSTEM_ERROR.getCode();
    }
}

pom文件,可能需要引入的依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- 加密依赖 -->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

        <!-- swagger依赖 -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.6.2</version>
        </dependency>

        <!-- hutool支持 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.20</version>
        </dependency>

        <!-- jackson-annotations 支持 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- jackson-databind 支持 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- jackson-datatype 支持, 以便正确序列化日期 -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- sa-token支持 -->
        <dependency>
            <groupId>cn.dev33</groupId>
            <artifactId>sa-token-spring-boot-starter</artifactId>
            <version>1.30.0</version>
        </dependency>
        <dependency>
            <groupId>cn.dev33</groupId>
            <artifactId>sa-token-alone-redis</artifactId>
            <version>1.30.0</version>
        </dependency>

        <!-- easyexcel支持 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

    </dependencies>

文章来源:https://blog.csdn.net/sungencheng/article/details/135201167
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。