0

How to convert string Date to Date?

I have a string "20210712" in the format yyyymmdd how to convert it into date...And how to get the day of It.

S4nj33v
  • 299
  • 3
  • 11

2 Answers2

5

You can do it with use of DateTimeFormatter and LocalDate:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate date = LocalDate.parse("20210712", formatter);
System.out.println(date);
System.out.println(date.getDayOfWeek());
System.out.println(date.getDayOfMonth());
System.out.println(date.getDayOfYear());

Output:

2021-07-12
MONDAY
12
193
Amon
  • 101
  • 5
  • I am new to JavaScript!. Tried pasting your code inside the script, it shows some errors. Not running, What should I do to run it without any error – S4nj33v Jul 14 '21 at 08:45
  • Java is different from JavaScript. The solution I proposed is in Java, as the original tag of your question, it won't work in JavaScript. – Amon Jul 14 '21 at 09:41
1

You can use String.substr to split the date string into its components. We'll use the + shorthand to convert each component into a number, then create a new Date object from it, using the Date constructor new Date(year, monthIndex, day).

NB: In JavaScript we pass the monthIndex to the Date rather than the month number, so July is represented as monthIndex = 6;

To get the day of the month from your date, you'll need Date.getDate().

To get the day of the week from your date, you'll need Date.getDay(), this will return 0 - 6 (Sunday (0) -> Saturday (6))

To get the day of the week as a string from your date, you can use Intl.DateTimeFormat, this will return 'Monday' -> 'Sunday'.

const timestamp = "20210712";
const year = +timestamp.substr(0,4);
const monthIndex = +timestamp.substr(4,2) - 1;
const day = +timestamp.substr(6,2);

console.log("Timestamp:", timestamp)
console.log("Date components:", JSON.stringify({ year, monthIndex, day }))

const date = new Date(year ,monthIndex, day);
console.log('Date:', date.toDateString());
console.log('Day of Month:', date.getDate());

// Sunday - Saturday : 0 - 6
console.log('Day of Week (0-6):', date.getDay());
console.log('Day of Week (string):', new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(date))
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    I am new to javascript, I am not able to run this code...How to run it in web to get the output. – S4nj33v Jul 14 '21 at 13:20
  • I would suggest using something like https://jsfiddle.net/ to test simple functions like this. You can paste any code you wish to test into the JavaScript window. I've created a fiddle you can test: https://jsfiddle.net/su3baj0n/. NB: Press F12 before running so you can see the console output. You could also create a node.js script. Install node.js, then create your script, say script.js and in your command window: node script.js. – Terry Lennox Jul 14 '21 at 13:25