将系统时间转换为字符串到Timestamp

问题描述 投票:-1回答:3

我正在尝试使用Java来获取计算机的时间并使用SimpleDateFormat对象按特定顺序对其进行格式化,但它不会格式化;请帮忙。

这是我的代码:

java.util.Date parsedDate = null;      
try {   
    DateFormat dateFormat = new SimpleDateFormat("HH:mm");  
    parsedDate = dateFormat.parse(dateFormat.format(new java.util.Date()));
}catch(ParseException e){
}  
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
java date timestamp simpledateformat time-format
3个回答
1
投票

tl;dr

LocalTime
    .now( ZoneId.of( "Pacific/Auckland" ) ) 
    .toString() 

java.time

您正在使用现在由现代java.time类取代的麻烦的旧遗留类。完全避免使用旧课程。

获取UTC的当前时刻,分辨率最高可达纳秒。

Instant instant = Instant.now() ;

要通过特定区域的挂钟时间查看同一时刻,请应用时区。

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atone( z ) ;

要仅使用没有日期且没有时区的时间,请提取LocalTime对象。

LocalTime lt = zdt.toLocalTime() ;

如果通过“格式到特定顺序”,则意味着排序......这些对象知道如何排序。不需要用于排序的字符串。

List<LocalTime> times = new ArrayList<>() ;
times.add( lt ) ;
…
Collections.sort( times ) ;

生成一个字符串以显示给用户。默认情况下,java.time类使用标准的ISO 8601格式来生成/解析字符串。

String output = lt.toString() ;

对于其他格式,请使用DateTimeFormatter

DateTimeFormatter f = DateTimeFormatter.ofPattern( "HH:mm" ) ;
String output = lt.format( f ) ;

所有这些都已经在Stack Overflow上处理了很多次。搜索更多信息和讨论。


0
投票

嗨user8545027我修改了你的代码,它现在对我有用。我还使用ThreadLocal使SimpleDateFormat对MultiThreading安全。

package com.java;

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

public class Test {

    private ThreadLocal<SimpleDateFormat> threadSafeDateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("HH:mm");
        }
    };

    String formatDate() {
        SimpleDateFormat format = threadSafeDateFormat.get();
        String timeStamp = format.format(new Date());
        return timeStamp;
    }


    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.formatDate());
    }
}

如果有任何问题,请告诉我。希望这可以帮助。


-1
投票

使用:

public class Basics {

  public static void main(String[] args) {

    DateFormat dateFormat = new SimpleDateFormat("HH:mm");
    String date = dateFormat.format(System.currentTimeMillis());
    System.out.println(date);   
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.