Java实现时间与字符串互相转换的方法详解

0
(0)

Java编程中,时间字符串的转换操作非常常见。Java提供了丰富的API工具,如java.time包和SimpleDateFormat类,以简化这类操作的实现。本文通过实例演示如何高效完成日期与字符串的相互转换。

java.webp

日期格式化为字符串

借助java.time包中的DateTimeFormatter类,可以灵活实现日期对象到字符串的转换。下面展示两种典型用法:

使用预定义格式

通过内置的ISO标准格式进行转换:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateFormatExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        String formattedDate = now.format(formatter);
        System.out.println("ISO格式日期时间: " + formattedDate);
    }
}

自定义格式

创建自定义格式模板来适配业务需求:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CustomFormatExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = now.format(formatter);
        System.out.println("自定义格式日期时间: " + formattedDate);
    }
}

字符串解析为日期

需确保字符串格式与解析器格式完全一致。以下是两种典型场景的实现:

解析ISO格式字符串

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ParseISODateExample {
    public static void main(String[] args) {
        String isoDate = "2023-10-11T12:34:56";
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        LocalDateTime date = LocalDateTime.parse(isoDate, formatter);
        System.out.println("解析后的日期时间: " + date);
    }
}

解析自定义格式字符串

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ParseCustomDateExample {
    public static void main(String[] args) {
        String customDate = "2023-10-11 12:34:56";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime date = LocalDateTime.parse(customDate, formatter);
        System.out.println("解析后的日期时间: " + date);
    }
}

时区处理示例

通过ZonedDateTime类可实现跨时区日期转换:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class TimeZoneExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        ZoneId zoneId = ZoneId.of("America/New_York");
        ZonedDateTime zonedDateTime = ZonedDateTime.of(now, zoneId);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
        String formattedDate = zonedDateTime.format(formatter);
        System.out.println("纽约时区日期时间: " + formattedDate);
    }
}

方法补充与经典案例

以下是关于时间到字符串转换的多样化实现方案:

使用传统SimpleDateFormat方法:

import java.util.Date;
import java.text.SimpleDateFormat;

public class Main {
    public static void main(String[] args) {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = dateFormat.format(currentDate);
        System.out.println(dateString);
    }
}

使用LocalDateTime类的现代写法:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateTimeString = currentDateTime.format(formatter);
        System.out.println(dateTimeString);
    }
}

经典转换场景实现

  1. 时间戳转日期格式
  2. import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class LongToString {
        public static void main(String[] args) {
            String time = "1256006105375";
            Date date = new Date(Long.parseLong(time));
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time = formatter.format(date);
            System.out.println(time);
        }
    }
    
  3. 字符串转Date对象
  4. import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class StringToDate {
        public static void main(String[] args) throws Exception {
            String time = "2010-11-20 11:10:10";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = formatter.parse(time);
            System.out.println(date);
        }
    }
    
  5. 获取当前系统时间
  6. 输出完整日期时间:

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class StringToDate {
        public static void main(String[] args) throws Exception {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = formatter.format(date);
            System.out.println(time);
        }
    }
    
  7. 仅输出时间部分
  8. import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class StringToDate {
        public static void main(String[] args) throws Exception {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            String time = formatter.format(date);
            System.out.println(time);
        }
    }
    
  9. 转换特殊格式字符串
  10. import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class StringToDate {
        public static void main(String[] args) throws Exception {
            String time = "20101125102503";
            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time = formatter2.format(formatter1.parse(time));
            System.out.println(time);
        }
    }
    

总结

通过Java的java.time包和传统SimpleDateFormat,开发者可以轻松应对99%的日期转换需求。推荐使用java.time包的线程安全设计,尤其是处理国际化场景时。掌握日期格式化控制可以提升代码可读性,并规避时区偏移等常见错误,建议所有开发人员重点掌握这部分核心API。

文章目录

共计0人评分,平均0

到目前为止还没有投票~

很抱歉,这篇文章对您没有用!

告诉我们如何改善这篇文章?

文章标题:Java实现时间与字符串互相转换的方法详解
更新时间:2025年04月18日 21时01分50秒
文章链接:https://www.sokb.cn/soyi-5157.html
文章版权:易搜资源网所发布的内容,部分为原创文章,转载注明来源,网络转载文章如有侵权请联系我们!
(0)
上一篇 2025 年 4 月 18 日 下午8:47
下一篇 2025 年 4 月 18 日 下午9:03

相关推荐

发表回复

登录后才能评论