Class -- 04 -- Date类常用方法解析

原文链接:Class – 04 – Date类常用方法解析


相关文章:


这次主要整理下 Java 中 Date 类的常用方法


一、Date 类的定义

  • Date 类位于 java.util 包中,主要用来封装当前的日期和时间

  • Date 类提供两个构造函数来实例化 Date 对象 (其余构造方法已经过时了)

    • Date()

      • 使用当前日期和时间来初始化对象
    • Date(long milliseconds)

      • 接收一个 long 类型的参数,该参数是从 1970-01-01 00:00:00.000 到当前时间的毫秒数
    Date date = new Date();
    // 打印Date对象
    // Sat:表示周六
    // Aug:表示八月
    // GMT:格林威治标准时间
    // GMT+08:00:东八区即标准北京时间
    System.out.println(date); // Sat Aug 11 17:03:32 GMT+08:00 2018
    

二、Date 类的常用方法

  • getTime()

    • 获取时间毫秒数

      Date date = new Date();
      System.out.println(date.getTime()); // 1533978518866
      

  • setTime(long milliseconds)

    • 设置时间毫秒数

      Date date = new Date();
      date.setTime(100);
      System.out.println(date); // Thu Jan 01 08:00:00 GMT+08:00 1970
      

  • equals(Object obj)

    • 用于比较两个时间是否相等

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date1 = sdf.parse("2018-08-10 08:08:123");
      Date date2 = sdf.parse("2018-08-10 08:08:123");
      System.out.println(date1.equals(date2)); // true
      
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date1 = sdf.parse("2018-08-10 08:08:123");
      Date date2 = sdf.parse("2018-08-11 08:08:123");
      System.out.println(date1.equals(date2)); // false
      

  • after(Date when)

    • 校验目标日期是否在参数日期之后

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date1 = sdf.parse("2018-08-10 08:08:123");
      Date date2 = sdf.parse("2018-08-09 08:08:123");
      System.out.println(date1.after(date2)); // true
      

  • before(Date when)

    • 校验目标日期是否在参数日期之前

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date1 = sdf.parse("2018-08-10 08:08:123");
      Date date2 = sdf.parse("2018-08-09 08:08:123");
      System.out.println(date1.before(date2)); // false
      

  • compareTo(Date anotherDate)

    • 对两个Date对象进行比较

    • 如果目标日期等于参数日期,则返回 0

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date1 = sdf.parse("2018-08-10 08:08:123");
      Date date2 = sdf.parse("2018-08-10 08:08:123");
      System.out.println(date1.compareTo(date2)); // 0
      
    • 如果目标日期在参数日期之后,则返回 1

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date1 = sdf.parse("2018-08-11 08:08:123");
      Date date2 = sdf.parse("2018-08-10 08:08:123");
      System.out.println(date1.compareTo(date2)); // 1
      
    • 如果目标日期在参数日期之前,则返回 -1

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date1 = sdf.parse("2018-08-09 08:08:123");
      Date date2 = sdf.parse("2018-08-10 08:08:123");
      System.out.println(date1.compareTo(date2)); // -1
      

  • toInstant()

    • Instant 输出的是标准时间,即格林威治标准时间,而 Date 输出的是北京时间,两者相差 8 个小时

    • 返回一条时间线上与此日期相同的一个点

      Date date = new Date();
      // Instant:java8的新特性,表示时间线中的一个特定时刻
      Instant instant = date.toInstant();
      // 标准时间,精确到纳秒 
      System.out.println(instant); // 2018-08-11T03:11:59.110Z
      // 将标准时间修改为北京时间,即+8小时
      System.out.println(instant.plusMillis(TimeUnit.HOURS.toMillis(8))); // 2018-08-11T11:11:59.110Z
      // 北京时间,精确到毫秒
      System.out.println(date); // Sat Aug 11 11:11:59 GMT+08:00 2018
      
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot和Spring Security是非常常用的Java框架和库,用于构建安全和可扩展的Web应用程序。JWT(JSON Web Token)是一种用于在网络应用间安全传递身份验证和声明信息的标准。 要在Spring Boot中使用Spring Security和JWT,你需要进行以下步骤: 1. 添加依赖:在你的项目的pom.xml文件中添加Spring Security和JWT的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2. 创建JWT工具:编写一个JWT工具,用于生成和解析JWT。 ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.userdetails.UserDetails; import java.util.Date; import java.util.HashMap; import java.util.Map; public class JwtUtil { private static final String SECRET_KEY = "your-secret-key"; private static final long EXPIRATION_TIME = 864_000_000; // 10 days public static String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return Jwts.builder() .setClaims(claims) .setSubject(userDetails.getUsername()) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, SECRET_KEY) .compact(); } public static String extractUsername(String token) { return extractClaims(token).getSubject(); } public static Date extractExpiration(String token) { return extractClaims(token).getExpiration(); } private static Claims extractClaims(String token) { return Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); } } ``` 3. 配置Spring Security:创建一个继承自WebSecurityConfigurerAdapter的配置,用于配置Spring Security。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Bean public PasswordEncoder passwordEncoder() { return new Pbkdf2PasswordEncoder(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } ``` 4. 创建UserDetails实现:实现Spring Security的UserDetails接口,用于获取用户信息。 ```java import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.List; public class CustomUserDetails implements UserDetails { private String username; private String password; public CustomUserDetails(String username, String password) { this.username = username; this.password = password; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return List.of(() -> "ROLE_USER"); } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } // Other UserDetails methods... @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } ``` 5. 创建认证和授权的Controller:创建一个RestController,用于处理用户认证和授权的请求。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/auth") public class AuthController { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @PostMapping("/login") public ResponseEntity<String> login(@RequestBody AuthRequest authRequest) { authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword()) ); UserDetails userDetails = userDetailsService.loadUserByUsername(authRequest.getUsername()); String token = JwtUtil.generateToken(userDetails); return ResponseEntity.ok(token); } } class AuthRequest { private String username; private String password; // getters and setters... } ``` 这样,你就可以在Spring Boot应用程序中使用Spring Security和JWT来实现认证和授权了。当用户登录时,会生成一个JWT,并在以后的请求中使用该JWT进行身份验证。 请注意,以上代码只是一个简单的示例,你可能需要根据你的实际需求进行适当的修改和扩展。另外,确保保护敏感信息(如密钥)的安全。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值