Converting date into string format in Python, Javascript, Java and Ruby

By | December 30, 2023

Python
from datetime import datetime
date_object = datetime.now()
date_string = date_object.strftime(“%Y-%m-%d %H:%M:%S”)
print(date_string)

JavaScript
const currentDate = new Date();
const dateString = currentDate.toISOString(); // Adjust the format as needed
console.log(dateString);

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

public class DateToString {
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);
}
}

Ruby
require ‘date’
current_date = DateTime.now
date_string = current_date.strftime(‘%Y-%m-%d %H:%M:%S’)
puts date_string

These examples provide a basic format for the date string, but you can customize the format string according to your requirements. Adjust the format specifier inside the strftime method or the format string passed to ToString based on the desired output.

Leave a Reply

Your email address will not be published. Required fields are marked *