-4

Given Format: 2017-03-08 13:27:00

I want to spilt it into 2 strings 1 for date and 1 for time for

E.g.
08-03-2017
13:27:00

Tim
  • 41,901
  • 18
  • 127
  • 145
Hetal1311
  • 364
  • 3
  • 14
  • 1
    Well, I would parse the whole thing using SimpleDateFormat, then format again using two different SimpleDateFormat instances, one for the time and one for the date. What have you tried so far? – Jon Skeet Mar 30 '17 at 07:48
  • `str.split("\\s");` zeroth index would be date, first would be time. Possible duplicate of [How to split a string in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Raman Sahasi Mar 30 '17 at 07:49
  • Can you plz give me format of SimpleDateFormat instances – Hetal1311 Mar 30 '17 at 07:53
  • I have already tried SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy"); – Hetal1311 Mar 30 '17 at 07:54

3 Answers3

3

First if your date in String format then Parse it to Date and then try it.

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

    public class Main {

        public static void main(String[] args) {
            Date today = new Date();
            DateFormat timeFormat = SimpleDateFormat.getTimeInstance();
            DateFormat dateFormat = SimpleDateFormat.getDateInstance();
            timeFormat.format(today);
            dateFormat.format(today);
            System.out.println("Time: " + timeFormat.format(today));
            System.out.println("Date: " + dateFormat.format(today));
        }
    }

Output:

Time: 1:25:31 AM
Date: 31 Mar, 2017

Hope this help !

Jaimin Prajapati
  • 341
  • 5
  • 14
1

try this

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

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2017-03-08 13:27:00";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"  
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("Date :"+dt1.format(date));

          dt1 = new SimpleDateFormat("HH:mm:ss");
            System.out.println("Time :"+dt1.format(date));
    }

}

It gives output like this

Date :2017-03-08 Time :13:27:00

Dhiraj
  • 1,430
  • 11
  • 21
1

Try this :

String datetime= "2017-03-08 13:27:00";
String[] divide= datetime.split("\\s");
String date = divide[0]; //2017-03-08
String time= divide[1]; // 13:27:00
Pranita
  • 803
  • 7
  • 16