java create date object using a value string

2020-02-08 11:19发布

I am using this to get the current time :

java.util.Calendar cal = java.util.Calendar.getInstance();
    System.out.println(new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
            .format(cal.getTime()));

I want to put the value (which I print it) into a date object, I tried this:

Date currentDate = new Date(value);

but eclipse tells me that this function is not good.

Edit the value is the value that I printed to you using system.out.println

标签: java date
9条回答
够拽才男人
2楼-- · 2020-02-08 11:42

Try this :-

try{
        String valuee="25/04/2013";
        Date currentDate =new SimpleDateFormat("dd/MM/yyyy").parse(valuee);
        System.out.println("Date is ::"+currentDate);
        }catch(Exception e){
            System.out.println("Error::"+e);
            e.printStackTrace();
        }

Output:-

   Date is ::Thu Apr 25 00:00:00 GMT+05:30 2013

Your value should be proper format.

In your question also you have asked for this below :-

   Date currentDate = new Date(value);

This style of date constructor is already deprecated.So, its no more use.Being we know that Date has 6 constructor.Read more

查看更多
Luminary・发光体
3楼-- · 2020-02-08 11:46

Use SimpleDateFormat parse method:

import java.text.DateFormat;
import java.text.SimpleDateFormat;

String inputString = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(inputString, dateFormat );

Since we have Java 8 with LocalDate I would suggest use next:

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

String inputString = "11-11-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate inputDate = LocalDate.parse(inputString);
查看更多
放我归山
4楼-- · 2020-02-08 11:46
 import java.util.Date;
 import java.text.SimpleDateFormat;

Above is the import method, below is the simple code for Date

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();

 system.out.println((dateFormat.format(date))); 
查看更多
登录 后发表回答