Jquery Date Format Conversion [duplicate] - javascript

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));
The code above gives me the same date format, sun may 11,2014. How can I fix this?

Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:
let yourDate = new Date()
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
Edit: #exbuddha wrote this to handle time zone in the comments:
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]

You can do:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate('Sun May 11,2014'));
Usage example:
console.log(formatDate('Sun May 11,2014'));
Output:
2014-05-11
Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/

I use this way to get the date in format yyyy-mm-dd :)
var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);

2020 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
const testCases = [
new Date().toLocaleDateString(), // 8/19/2020
new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}),
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}), // 09 (just the hour)
]
for (const testData of testCases) {
console.log(testData)
}
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.

The simplest way to convert your date to the yyyy-mm-dd format, is to do this:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
How it works:
new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings)
new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset
.toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
.split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"]
[0] takes the first element of that array
Demo
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
Note :
The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie
pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.

A combination of some of the answers:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');

format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
Result:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11

If you don't have anything against using libraries, you could just use the Moments.js library like so:
var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

You can use toLocaleDateString('fr-CA') on Date object
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));
Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?
'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'
var localesList = ["af-ZA",
"am-ET",
"ar-AE",
"ar-BH",
"ar-DZ",
"ar-EG",
"ar-IQ",
"ar-JO",
"ar-KW",
"ar-LB",
"ar-LY",
"ar-MA",
"arn-CL",
"ar-OM",
"ar-QA",
"ar-SA",
"ar-SY",
"ar-TN",
"ar-YE",
"as-IN",
"az-Cyrl-AZ",
"az-Latn-AZ",
"ba-RU",
"be-BY",
"bg-BG",
"bn-BD",
"bn-IN",
"bo-CN",
"br-FR",
"bs-Cyrl-BA",
"bs-Latn-BA",
"ca-ES",
"co-FR",
"cs-CZ",
"cy-GB",
"da-DK",
"de-AT",
"de-CH",
"de-DE",
"de-LI",
"de-LU",
"dsb-DE",
"dv-MV",
"el-GR",
"en-029",
"en-AU",
"en-BZ",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JM",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-TT",
"en-US",
"en-ZA",
"en-ZW",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-CR",
"es-DO",
"es-EC",
"es-ES",
"es-GT",
"es-HN",
"es-MX",
"es-NI",
"es-PA",
"es-PE",
"es-PR",
"es-PY",
"es-SV",
"es-US",
"es-UY",
"es-VE",
"et-EE",
"eu-ES",
"fa-IR",
"fi-FI",
"fil-PH",
"fo-FO",
"fr-BE",
"fr-CA",
"fr-CH",
"fr-FR",
"fr-LU",
"fr-MC",
"fy-NL",
"ga-IE",
"gd-GB",
"gl-ES",
"gsw-FR",
"gu-IN",
"ha-Latn-NG",
"he-IL",
"hi-IN",
"hr-BA",
"hr-HR",
"hsb-DE",
"hu-HU",
"hy-AM",
"id-ID",
"ig-NG",
"ii-CN",
"is-IS",
"it-CH",
"it-IT",
"iu-Cans-CA",
"iu-Latn-CA",
"ja-JP",
"ka-GE",
"kk-KZ",
"kl-GL",
"km-KH",
"kn-IN",
"kok-IN",
"ko-KR",
"ky-KG",
"lb-LU",
"lo-LA",
"lt-LT",
"lv-LV",
"mi-NZ",
"mk-MK",
"ml-IN",
"mn-MN",
"mn-Mong-CN",
"moh-CA",
"mr-IN",
"ms-BN",
"ms-MY",
"mt-MT",
"nb-NO",
"ne-NP",
"nl-BE",
"nl-NL",
"nn-NO",
"nso-ZA",
"oc-FR",
"or-IN",
"pa-IN",
"pl-PL",
"prs-AF",
"ps-AF",
"pt-BR",
"pt-PT",
"qut-GT",
"quz-BO",
"quz-EC",
"quz-PE",
"rm-CH",
"ro-RO",
"ru-RU",
"rw-RW",
"sah-RU",
"sa-IN",
"se-FI",
"se-NO",
"se-SE",
"si-LK",
"sk-SK",
"sl-SI",
"sma-NO",
"sma-SE",
"smj-NO",
"smj-SE",
"smn-FI",
"sms-FI",
"sq-AL",
"sr-Cyrl-BA",
"sr-Cyrl-CS",
"sr-Cyrl-ME",
"sr-Cyrl-RS",
"sr-Latn-BA",
"sr-Latn-CS",
"sr-Latn-ME",
"sr-Latn-RS",
"sv-FI",
"sv-SE",
"sw-KE",
"syr-SY",
"ta-IN",
"te-IN",
"tg-Cyrl-TJ",
"th-TH",
"tk-TM",
"tn-ZA",
"tr-TR",
"tt-RU",
"tzm-Latn-DZ",
"ug-CN",
"uk-UA",
"ur-PK",
"uz-Cyrl-UZ",
"uz-Latn-UZ",
"vi-VN",
"wo-SN",
"xh-ZA",
"yo-NG",
"zh-CN",
"zh-HK",
"zh-MO",
"zh-SG",
"zh-TW",
"zu-ZA"
];
localesList.forEach(lcl => {
if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {
console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));
}
});

The 2021 solution using Intl.
The new Intl Object is now supported on all browsers.
You can choose the format by choosing a "locale" that uses the required format.
The Swedish locale uses the format "yyyy-mm-dd":
// Create a date
const date = new Date(2021, 10, 28);
// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');
// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"
Downsides of using Intl:
You cannot "unformat" or "parse" strings using this method
You have to search for the required format (for instance on Wikipedia) and cannot use a format-string like "yyyy-mm-dd"

Simply use this:
var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Simple and sweet ;)

Shortest
.toJSON().slice(0,10);
var d = new Date('Sun May 11,2014' +' UTC'); // Parse as UTC
let str = d.toJSON().slice(0,10); // Show as UTC
console.log(str);

toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.
The following method should return what you need.
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/

In the most of cases (no time zone handling) this is enough:
date.toISOString().substring(0,10)
Example
var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04

Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.
function formatDate(date) {
var year = date.getFullYear().toString();
var month = (date.getMonth() + 101).toString().substring(1);
var day = (date.getDate() + 100).toString().substring(1);
return year + "-" + month + "-" + day;
}
//Usage example:
alert(formatDate(new Date()));

new Date('Tue Nov 01 2022 22:14:53 GMT-0300').toLocaleDateString('en-CA');
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Try this!

When ES2018 rolls around (works in chrome) you can simply regex it
(new Date())
.toISOString()
.replace(
/^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
'$<year>-$<month>-$<day>'
)
2020-07-14
Or if you'd like something pretty versatile with no libraries whatsoever
(new Date())
.toISOString()
.match(
/^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
)
.groups
Which results in extracting the following
{
H: "8"
HH: "08"
M: "45"
MM: "45"
S: "42"
SS: "42"
SSS: "42.855"
d: "14"
dd: "14"
m: "7"
mm: "07"
timezone: "Z"
yy: "20"
yyyy: "2020"
}
Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> # $<H>:$<MM>') as at the top instead of .match(...).groups to get
14/7/'20 # 8:45

const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
You can make use of padstart.
padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.
join('-') concatenates an array, adding '-' symbol between every elements.
getMonth() starts at 0 hence the +1.

To consider the timezone also, this one-liner should be good without any library:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]

You can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
Use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get the date string by using this method:
getString

I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.
new Date().format("%Y-%m-%d")

Unfortunately, JavaScript's Date object has many pitfalls. Any solution based on Date's builtin toISOString has to mess with the timezone, as discussed in some other answers to this question. The clean solution to represent an ISO-8601 date (without time) is given by Temporal.PlainDate from the Temporal proposal. As of February 2021, you have to choose the workaround that works best for you.
use Date with vanilla string concatenation
Assuming that your internal representation is based on Date, you can perform manual string concatenation. The following code avoids some of Date's pitfalls (timezone, zero-based month, missing 2-digit formatting), but there might be other issues.
function vanillaToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
const dd = String(date.getDate()).padStart(2, "0");
if (yyyy < 1583) {
// TODO: decide how to support dates before 1583
throw new Error(`dates before year 1583 are not supported`);
}
const formatted = `${yyyy}-${mm}-${dd}`;
console.log("vanilla", formatted);
}
use Date with helper library (e.g. formatISO from date-fns)
This is a popular approach, but you are still forced to handle a calendar date as a Date, which represents
a single moment in time in a platform-independent format
The following code should get the job done, though:
import { formatISO } from "date-fns";
function dateFnsToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const formatted = formatISO(date, { representation: "date" });
console.log("date-fns", formatted);
}
find a library that properly represents dates and times
I wish there was a clean and battle-tested library that brings its own well-designed date–time representations. A promising candidate for the task in this question was LocalDate from #js-joda/core, but the library is less active than, say, date-fns. When playing around with some example code, I also had some issues after adding the optional #js-joda/timezone.
However, the core functionality works and looks very clean to me:
import { LocalDate, Month } from "#js-joda/core";
function jodaDateOnlyIso8601() {
const someDay = LocalDate.of(2014, Month.MAY, 11);
const formatted = someDay.toString();
console.log("joda", formatted);
}
experiment with the Temporal-proposal polyfill
This is not recommended for production, but you can import the future if you wish:
import { Temporal } from "proposal-temporal";
function temporalDateOnlyIso8601() {
// yep, month is one-based here (as of Feb 2021)
const plainDate = new Temporal.PlainDate(2014, 5, 11);
const formatted = plainDate.toString();
console.log("proposal-temporal", formatted);
}

Here is one way to do it:
var date = Date.parse('Sun May 11,2014');
function format(date) {
date = new Date(date);
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return year + '-' + month + '-' + day;
}
console.log(format(date));

Date.js is great for this.
require("datejs")
(new Date()).toString("yyyy-MM-dd")

Simply Retrieve year, month, and day, and then put them together.
function dateFormat(date) {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
console.log(dateFormat(new Date()));

None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.
This is what I came up with:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
So for example, localDay(new Date("2017-08-24T03:29:22.099Z")) will return "2017-08-23" even though it's already the 24th at UTC.
You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.

A few of the previous answer were OK, but they weren't very flexible. I wanted something that could really handle more edge cases, so I took #orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand
// to '10' and specifying yy for just two year digits '01' instead
// of '2001'. One expands, the other contracts.
//
// So Constrict Years but Expand All Else
if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to
// multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
Example usage:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');

If you use momentjs, now they include a constant for that format YYYY-MM-DD:
date.format(moment.HTML5_FMT.DATE)

You can use this function for better format and easy of use:
function convert(date) {
const d = Date.parse(date)
const date_obj = new Date(d)
return `${date_obj.getFullYear()}-${date_obj.toLocaleString("default", { month: "2-digit" })}-${date_obj.toLocaleString("default", { day: "2-digit"})}`
}
This function will format the month as 2-digit output as well as the days

Yet another combination of the answers. Nicely readable, but a little lengthy.
function getCurrentDayTimestamp() {
const d = new Date();
return new Date(
Date.UTC(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds()
)
// `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
// and we want the first part ("2017-08-22")
).toISOString().slice(0, 10);
}

Related

Playwright Current Date +1 Day [duplicate]

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));
The code above gives me the same date format, sun may 11,2014. How can I fix this?
Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:
let yourDate = new Date()
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
Edit: #exbuddha wrote this to handle time zone in the comments:
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
You can do:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate('Sun May 11,2014'));
Usage example:
console.log(formatDate('Sun May 11,2014'));
Output:
2014-05-11
Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
I use this way to get the date in format yyyy-mm-dd :)
var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);
2020 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
const testCases = [
new Date().toLocaleDateString(), // 8/19/2020
new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}),
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}), // 09 (just the hour)
]
for (const testData of testCases) {
console.log(testData)
}
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
The simplest way to convert your date to the yyyy-mm-dd format, is to do this:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
How it works:
new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings)
new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset
.toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
.split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"]
[0] takes the first element of that array
Demo
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
Note :
The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie
pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.
A combination of some of the answers:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
Result:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
If you don't have anything against using libraries, you could just use the Moments.js library like so:
var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
You can use toLocaleDateString('fr-CA') on Date object
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));
Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?
'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'
var localesList = ["af-ZA",
"am-ET",
"ar-AE",
"ar-BH",
"ar-DZ",
"ar-EG",
"ar-IQ",
"ar-JO",
"ar-KW",
"ar-LB",
"ar-LY",
"ar-MA",
"arn-CL",
"ar-OM",
"ar-QA",
"ar-SA",
"ar-SY",
"ar-TN",
"ar-YE",
"as-IN",
"az-Cyrl-AZ",
"az-Latn-AZ",
"ba-RU",
"be-BY",
"bg-BG",
"bn-BD",
"bn-IN",
"bo-CN",
"br-FR",
"bs-Cyrl-BA",
"bs-Latn-BA",
"ca-ES",
"co-FR",
"cs-CZ",
"cy-GB",
"da-DK",
"de-AT",
"de-CH",
"de-DE",
"de-LI",
"de-LU",
"dsb-DE",
"dv-MV",
"el-GR",
"en-029",
"en-AU",
"en-BZ",
"en-CA",
"en-GB",
"en-IE",
"en-IN",
"en-JM",
"en-MY",
"en-NZ",
"en-PH",
"en-SG",
"en-TT",
"en-US",
"en-ZA",
"en-ZW",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-CR",
"es-DO",
"es-EC",
"es-ES",
"es-GT",
"es-HN",
"es-MX",
"es-NI",
"es-PA",
"es-PE",
"es-PR",
"es-PY",
"es-SV",
"es-US",
"es-UY",
"es-VE",
"et-EE",
"eu-ES",
"fa-IR",
"fi-FI",
"fil-PH",
"fo-FO",
"fr-BE",
"fr-CA",
"fr-CH",
"fr-FR",
"fr-LU",
"fr-MC",
"fy-NL",
"ga-IE",
"gd-GB",
"gl-ES",
"gsw-FR",
"gu-IN",
"ha-Latn-NG",
"he-IL",
"hi-IN",
"hr-BA",
"hr-HR",
"hsb-DE",
"hu-HU",
"hy-AM",
"id-ID",
"ig-NG",
"ii-CN",
"is-IS",
"it-CH",
"it-IT",
"iu-Cans-CA",
"iu-Latn-CA",
"ja-JP",
"ka-GE",
"kk-KZ",
"kl-GL",
"km-KH",
"kn-IN",
"kok-IN",
"ko-KR",
"ky-KG",
"lb-LU",
"lo-LA",
"lt-LT",
"lv-LV",
"mi-NZ",
"mk-MK",
"ml-IN",
"mn-MN",
"mn-Mong-CN",
"moh-CA",
"mr-IN",
"ms-BN",
"ms-MY",
"mt-MT",
"nb-NO",
"ne-NP",
"nl-BE",
"nl-NL",
"nn-NO",
"nso-ZA",
"oc-FR",
"or-IN",
"pa-IN",
"pl-PL",
"prs-AF",
"ps-AF",
"pt-BR",
"pt-PT",
"qut-GT",
"quz-BO",
"quz-EC",
"quz-PE",
"rm-CH",
"ro-RO",
"ru-RU",
"rw-RW",
"sah-RU",
"sa-IN",
"se-FI",
"se-NO",
"se-SE",
"si-LK",
"sk-SK",
"sl-SI",
"sma-NO",
"sma-SE",
"smj-NO",
"smj-SE",
"smn-FI",
"sms-FI",
"sq-AL",
"sr-Cyrl-BA",
"sr-Cyrl-CS",
"sr-Cyrl-ME",
"sr-Cyrl-RS",
"sr-Latn-BA",
"sr-Latn-CS",
"sr-Latn-ME",
"sr-Latn-RS",
"sv-FI",
"sv-SE",
"sw-KE",
"syr-SY",
"ta-IN",
"te-IN",
"tg-Cyrl-TJ",
"th-TH",
"tk-TM",
"tn-ZA",
"tr-TR",
"tt-RU",
"tzm-Latn-DZ",
"ug-CN",
"uk-UA",
"ur-PK",
"uz-Cyrl-UZ",
"uz-Latn-UZ",
"vi-VN",
"wo-SN",
"xh-ZA",
"yo-NG",
"zh-CN",
"zh-HK",
"zh-MO",
"zh-SG",
"zh-TW",
"zu-ZA"
];
localesList.forEach(lcl => {
if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {
console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));
}
});
The 2021 solution using Intl.
The new Intl Object is now supported on all browsers.
You can choose the format by choosing a "locale" that uses the required format.
The Swedish locale uses the format "yyyy-mm-dd":
// Create a date
const date = new Date(2021, 10, 28);
// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');
// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"
Downsides of using Intl:
You cannot "unformat" or "parse" strings using this method
You have to search for the required format (for instance on Wikipedia) and cannot use a format-string like "yyyy-mm-dd"
Simply use this:
var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Simple and sweet ;)
Shortest
.toJSON().slice(0,10);
var d = new Date('Sun May 11,2014' +' UTC'); // Parse as UTC
let str = d.toJSON().slice(0,10); // Show as UTC
console.log(str);
toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.
The following method should return what you need.
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
In the most of cases (no time zone handling) this is enough:
date.toISOString().substring(0,10)
Example
var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04
Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.
function formatDate(date) {
var year = date.getFullYear().toString();
var month = (date.getMonth() + 101).toString().substring(1);
var day = (date.getDate() + 100).toString().substring(1);
return year + "-" + month + "-" + day;
}
//Usage example:
alert(formatDate(new Date()));
new Date('Tue Nov 01 2022 22:14:53 GMT-0300').toLocaleDateString('en-CA');
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Try this!
When ES2018 rolls around (works in chrome) you can simply regex it
(new Date())
.toISOString()
.replace(
/^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
'$<year>-$<month>-$<day>'
)
2020-07-14
Or if you'd like something pretty versatile with no libraries whatsoever
(new Date())
.toISOString()
.match(
/^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
)
.groups
Which results in extracting the following
{
H: "8"
HH: "08"
M: "45"
MM: "45"
S: "42"
SS: "42"
SSS: "42.855"
d: "14"
dd: "14"
m: "7"
mm: "07"
timezone: "Z"
yy: "20"
yyyy: "2020"
}
Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> # $<H>:$<MM>') as at the top instead of .match(...).groups to get
14/7/'20 # 8:45
const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
You can make use of padstart.
padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.
join('-') concatenates an array, adding '-' symbol between every elements.
getMonth() starts at 0 hence the +1.
To consider the timezone also, this one-liner should be good without any library:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
You can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
Use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get the date string by using this method:
getString
I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.
new Date().format("%Y-%m-%d")
Unfortunately, JavaScript's Date object has many pitfalls. Any solution based on Date's builtin toISOString has to mess with the timezone, as discussed in some other answers to this question. The clean solution to represent an ISO-8601 date (without time) is given by Temporal.PlainDate from the Temporal proposal. As of February 2021, you have to choose the workaround that works best for you.
use Date with vanilla string concatenation
Assuming that your internal representation is based on Date, you can perform manual string concatenation. The following code avoids some of Date's pitfalls (timezone, zero-based month, missing 2-digit formatting), but there might be other issues.
function vanillaToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
const dd = String(date.getDate()).padStart(2, "0");
if (yyyy < 1583) {
// TODO: decide how to support dates before 1583
throw new Error(`dates before year 1583 are not supported`);
}
const formatted = `${yyyy}-${mm}-${dd}`;
console.log("vanilla", formatted);
}
use Date with helper library (e.g. formatISO from date-fns)
This is a popular approach, but you are still forced to handle a calendar date as a Date, which represents
a single moment in time in a platform-independent format
The following code should get the job done, though:
import { formatISO } from "date-fns";
function dateFnsToDateOnlyIso8601() {
// month May has zero-based index 4
const date = new Date(2014, 4, 11);
const formatted = formatISO(date, { representation: "date" });
console.log("date-fns", formatted);
}
find a library that properly represents dates and times
I wish there was a clean and battle-tested library that brings its own well-designed date–time representations. A promising candidate for the task in this question was LocalDate from #js-joda/core, but the library is less active than, say, date-fns. When playing around with some example code, I also had some issues after adding the optional #js-joda/timezone.
However, the core functionality works and looks very clean to me:
import { LocalDate, Month } from "#js-joda/core";
function jodaDateOnlyIso8601() {
const someDay = LocalDate.of(2014, Month.MAY, 11);
const formatted = someDay.toString();
console.log("joda", formatted);
}
experiment with the Temporal-proposal polyfill
This is not recommended for production, but you can import the future if you wish:
import { Temporal } from "proposal-temporal";
function temporalDateOnlyIso8601() {
// yep, month is one-based here (as of Feb 2021)
const plainDate = new Temporal.PlainDate(2014, 5, 11);
const formatted = plainDate.toString();
console.log("proposal-temporal", formatted);
}
Here is one way to do it:
var date = Date.parse('Sun May 11,2014');
function format(date) {
date = new Date(date);
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return year + '-' + month + '-' + day;
}
console.log(format(date));
Date.js is great for this.
require("datejs")
(new Date()).toString("yyyy-MM-dd")
Simply Retrieve year, month, and day, and then put them together.
function dateFormat(date) {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
console.log(dateFormat(new Date()));
None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.
This is what I came up with:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
So for example, localDay(new Date("2017-08-24T03:29:22.099Z")) will return "2017-08-23" even though it's already the 24th at UTC.
You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.
A few of the previous answer were OK, but they weren't very flexible. I wanted something that could really handle more edge cases, so I took #orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand
// to '10' and specifying yy for just two year digits '01' instead
// of '2001'. One expands, the other contracts.
//
// So Constrict Years but Expand All Else
if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to
// multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
Example usage:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
If you use momentjs, now they include a constant for that format YYYY-MM-DD:
date.format(moment.HTML5_FMT.DATE)
Yet another combination of the answers. Nicely readable, but a little lengthy.
function getCurrentDayTimestamp() {
const d = new Date();
return new Date(
Date.UTC(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds()
)
// `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
// and we want the first part ("2017-08-22")
).toISOString().slice(0, 10);
}
Reformatting a date string is fairly straightforward, e.g.
var s = 'Sun May 11,2014';
function reformatDate(s) {
function z(n){return ('0' + n).slice(-2)}
var months = [,'jan','feb','mar','apr','may','jun',
'jul','aug','sep','oct','nov','dec'];
var b = s.split(/\W+/);
return b[3] + '-' +
z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
z(b[2]);
}
console.log(reformatDate(s));

javascript format date to legible format

I have this code which is getting me the date in a ledgible format but it currently outputs this format 20200819 but I want to convert it to 2020-08-19 is this possible?
This is my code
const dateConverter = (dateIn) => {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1; // getMonth() is zero-based
var dd = dateIn.getDate();
return String(10000 * yyyy + 100 * mm + dd); // Leading zeros for mm and dd
}
var today = new Date();
console.log(dateConverter(today));
You don't need the converter function for that. Just use toLocaleDateString with a locale that has this format, like Sweden.
To get more certainty about the format, I have added two extensions:
console.log(new Date().toLocaleDateString("en-se"));
// To be explicit about the format of the numerical parts
console.log(new Date().toLocaleDateString("en-se",
{ year: "numeric", month: "2-digit", day: "2-digit" })
);
// To be explicit about the delimiter also:
console.log(new Date().toLocaleDateString("en-se",
{ year: "numeric", month: "2-digit", day: "2-digit" })
.replace(/\D/g, "-")
);
Alternative:
If you don't want to rely on the native toLocaleDateString function, then replace the following line in your code:
return String(10000 * yyyy + 100 * mm + dd)
with:
return String(10000 * yyyy + 100 * mm + dd).replace(/(....)(..)(..)/,"$1-$2-$3");
You can use padStart to create your own string like below, but I would reccomend looking into the date-fns or moment.js libraries, as they can handle this very nicely.
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
You could use template literals to get the format you want, im pretty sure their must be a simpler way but, this is as similar to your code as possible
const dateConverter = (dateIn) => {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth() + 1;
if (mm < 10) mm = `0${mm}`; // getMonth() is zero-based
var dd = dateIn.getDate();
if (dd < 10) dd = `0${dd}`;
return `${yyyy}-${mm}-${dd}`;
};
var today = new Date();
console.log(dateConverter(today));
Output as today : 2020-08-19
new Date().toISOString().slice(0, 10).split('-').reverse().join('/')
//use following date format methods and options.
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US
// US English uses month-day-year order
console.log(date.toLocaleDateString('en-US'));
// → "12/19/2012"
// British English uses day-month-year order
console.log(date.toLocaleDateString('en-GB'));
// → "20/12/2012"
// Korean uses year-month-day order
console.log(date.toLocaleDateString('ko-KR'));
// → "2012. 12. 20."
// Event for Persian, It's hard to manually convert date to Solar Hijri
console.log(date.toLocaleDateString('fa-IR'));
// → "۱۳۹۱/۹/۳۰"
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleDateString('ar-EG'));
// → "٢٠‏/١٢‏/٢٠١٢"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(date.toLocaleDateString('ja-JP-u-ca-japanese'));
// → "24/12/20"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleDateString(['ban', 'id']));
// → "20/12/2012"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

How to convert an ISO date to the date format yyyy-mm-dd?

How can I get a date having the format yyyy-mm-dd from an ISO 8601 date?
My 8601 date is
2013-03-10T02:00:00Z
How can I get the following?
2013-03-10
Just crop the string:
var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);
Or if you need only date out of string.
var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);
Try this
date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.
Update:-
As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.
date = new Date('2013-08-03T02:00:00Z');
year = date.getFullYear();
month = date.getMonth()+1;
dt = date.getDate();
if (dt < 10) {
dt = '0' + dt;
}
if (month < 10) {
month = '0' + month;
}
console.log(year+'-' + month + '-'+dt);
You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.
Or just extract the first part of your ISO string, it already contains what you want.
Here is an example by splitting on the T:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
And another example by extracting the 10 first characters:
"2013-03-10T02:00:00Z".substr(0, 10) // "2013-03-10"
This is what I do to get date only:
let isoDate = "2013-03-10T02:00:00Z";
alert(isoDate.split("T")[0]);
let isoDate = "2013-03-10T02:00:00Z";
var d = new Date(isoDate);
d.toLocaleDateString('en-GB'); // dd/mm/yyyy
d.toLocaleDateString('en-US'); // mm/dd/yyyy
Moment.js will handle date formatting for you. Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"
Moment.js is pretty big library to use for a single use case. I recommend using date-fns instead. It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options.
import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x
One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone. Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);.
For more complex conversions date-fns is the way to go.
UPDATE: This no longer works with Firefox and Chromium v110+ (Feb 2023) because the 'en-CA' locale now returns the US date format.
Using toLocaleDateString with the Canadian locale returns a date in ISO format.
function getISODate(date) {
return date.toLocaleDateString('en-ca');
}
getISODate(new Date()); // '2022-03-24'
To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!
An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain.
See this example:
const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);
console.log(timeZoneRelatedDate.toLocaleDateString(
'ja-JP',
{
year: 'numeric',
month: '2-digit',
day: '2-digit'
}
).replace(/\//gi,'-'));
// RESULT: "2020-01-14"
console.log(timeZoneRelatedDate.toISOString());
// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)
console.log(timeZoneRelatedDate.toISOString().slice(0,10));
// RESULT: "2020-01-13"
Use:
new Date().toISOString().substring(0, 10);
This will output the date in YYYY-MM-DD format:
let date = new Date();
date = date.toISOString().slice(0,10);
The best way to format is by using toLocaleDateString with options
const options = {year: 'numeric', month: 'numeric', day: 'numeric' };
const date = new Date('2013-03-10T02:00:00Z').toLocaleDateString('en-EN', options)
Check Date section for date options here https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Pass your date in the date object:
var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');
If you have a date object:
let date = new Date()
let result = date.toISOString().split`T`[0]
console.log(result)
or
let date = new Date()
let result = date.toISOString().slice(0, 10)
console.log(result)
To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:
var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));
A better version of answer by #Hozefa.
If you have date-fns installed, you could use formatISO function
const date = new Date(2019, 0, 2)
import { formatISO } from 'date-fns'
formatISO(date, { representation: 'date' }) // '2019-01-02' string
If you have the timezone you can do:
const myDate = "2022-10-09T18:30:00.000Z"
const requestTimezone = "Asia/Calcutta";
const newDate = new Date(myDate).toLocaleString("en-CA", {
dateStyle: "short",
timeZone: requestTimezone,
});
console.log(newDate)
>> 2022-10-10
Another outputs:
const myDate = "2022-10-02T21:00:00.000Z"
const requestTimezone = "Asia/Jerusalem";
>> 2022-10-03
const myDate = "2022-09-28T04:00:00.000Z"
const requestTimezone = "America/New_York";
>> 2022-09-28
I used this:
HTMLDatetoIsoDate(htmlDate){
let year = Number(htmlDate.toString().substring(0, 4))
let month = Number(htmlDate.toString().substring(5, 7))
let day = Number(htmlDate.toString().substring(8, 10))
return new Date(year, month - 1, day)
}
isoDateToHtmlDate(isoDate){
let date = new Date(isoDate);
let dtString = ''
let monthString = ''
if (date.getDate() < 10) {
dtString = '0' + date.getDate();
} else {
dtString = String(date.getDate())
}
if (date.getMonth()+1 < 10) {
monthString = '0' + Number(date.getMonth()+1);
} else {
monthString = String(date.getMonth()+1);
}
return date.getFullYear()+'-' + monthString + '-'+dtString
}
Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
alert(d.toLocaleDateString());
let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();
if (dd<10) {
dd = '0' + dd;
}
if (mm<10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
Many of these answers give potentially misleading output if one is looking for the day in the current timezone.
This function will output the day corresponding with the date's timezone offset:
const adjustDateToLocalTimeZoneDayString = (date?: Date) => {
if (!date) {
return undefined;
}
const dateCopy = new Date(date);
dateCopy.setTime(dateCopy.getTime() - dateCopy.getTimezoneOffset()*60*1000);
return dateCopy.toISOString().split('T')[0];
};
Tests:
it('return correct day even if timezone is included', () => {
// assuming the test is running in EDT timezone
// 11:34pm eastern time would be the next day in GMT
let result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0400'));
// Note: This is probably what a person wants, the date in the current timezone
expect(result).toEqual('2022-04-06');
// 11:34pm zulu time should be the same
result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0000'));
expect(result).toEqual('2022-04-06');
result = adjustDateToLocalTimeZoneDayString(undefined);
expect(result).toBeUndefined();
});
Misleading approach:
To demonstrate the issue with the other answers' direct ISOString().split() approach, note how the output below differs from what one might expect:
it('demonstrates how the simple ISOString().split() may be misleading', () => {
// Note this is the 7th
expect(new Date('Wed Apr 06 2022 23:34:17 GMT-0400').toISOString().split('T')[0]).toEqual('2022-04-07');
});
Simpler way to get Year Or Month
let isoDateTime = "2013-03-10T02:00:00Z";
console.log(isoDateTime.split("T")[0]); //2013-03-10
Using Split Method
console.log(isoDateTime.split("-")[0]); //2013
console.log(isoDateTime.split("-")[1]); //03
WARNING: Most of these answers are wrong.
That is because toISOString() always returns the UTC date, not local date. So, for example, if your UTC time is 0500 and your timezone is GMT-0800, the day returned by toISOString() will be the UTC day, which will be one day ahead of the local timezone day.
You need to first convert the date to the local date.
const date = new Date();
date.setTime(date.getTime() - date.getTimezoneOffset()*60*1000)
Now date.toISOString() will always return the proper date according to the local timezone.
But wait, there's more. If we are also using toTimeString() that will now be wrong because time is now local and toTimeString() assumes it is UTC and converts it. So we need to first extract toTimeString() as a variable before doing the conversion.
The Date() class in javascript is inconsistent because of this and should really be updated to avoid this confusion. The toISOString() and toTimeString() methods should both do the same default things with respect to timezone.
Use the below code. It is useful for you.
let currentDate = new Date()
currentDate.toISOString()

How can I get time from ISO 8601 time format in JavaScript?

This is my ISO formatted date. In here I want to get time like "11:00" by JavaScript.
I used this method:
new Date(Mydate).toLocaleString();
But it gave time as "16:30". Is there any format or method to do that in JavaScript? How can I get only time of that time zone.
var Mydate = "2012-10-16T11:00:28.556094Z";
Output will be the "11:00"
Modern approach, using ECMAScript Internationalization API built in to Node.js and most modern browsers:
const myDate = "2012-10-16T11:00:28.556094Z";
const time = new Date(myDate).toLocaleTimeString('en',
{ timeStyle: 'short', hour12: false, timeZone: 'UTC' });
// Output: "11:00"
Older approach, using moment.js:
var myDate = "2012-10-16T11:00:28.556094Z";
var time = moment.utc(myDate).format("HH:mm");
// Output: "11:00"
Use this:
var date = new Date(Mydate);
var time = ConvertNumberToTwoDigitString(date.getUTCHours()) +
":" + ConvertNumberToTwoDigitString(date.getUTCMinutes());
// Returns the given integer as a string and with 2 digits
// For example: 7 --> "07"
function ConvertNumberToTwoDigitString(n) {
return n > 9 ? "" + n : "0" + n;
}
Try this, I forget where I got this:
// --- Date ---
// convert ISO 8601 date string to normal JS Date object
// usage: (new Date()).setISO8601( "ISO8601 Time" )
Date.prototype.setISO8601 = function(string) {
var d, date, offset, regexp, time;
regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
d = string.match(new RegExp(regexp));
offset = 0;
date = new Date(d[1], 0, 1);
if (d[3]) date.setMonth(d[3] - 1);
if (d[5]) date.setDate(d[5]);
if (d[7]) date.setHours(d[7]);
if (d[8]) date.setMinutes(d[8]);
if (d[10]) date.setSeconds(d[10]);
if (d[12]) date.setMilliseconds(Number("0." + d[12]) * 1000);
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= (d[15] === '-' ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = Number(date) + (offset * 60 * 1000);
return this.setTime(Number(time));
};
Try this to grab the time from ISO date.
let Mydate = '2012-10-16T11:00:28.556094Z';
let result = Mydate .match(/\d\d:\d\d/);
console.log(result[0]);
The output will be,
11:00
be aware that older implementation of the toLocaleTimeString can behave differently depending on the browser's implementation.
Date: 2021-September-09
The locales and options arguments customize the behavior of the
function and let applications specify which language formatting
conventions should be used. In older implementations that ignore the
locales and options arguments, the locales and the form of the string
returned will be entirely implementation-dependent.
The implementation I recently used:
function getTimeFromISODateString(isoDateString) {
const date = new Date(isoDateString);
const hours = `0${date.getUTCHours()}`.slice(-2);
const minutes = `0${date.getUTCMinutes()}`.slice(-2);
const seconds = `0${date.getUTCSeconds()}`.slice(-2);
return `${hours}:${minutes}:${seconds}`;
}
This answer failed for me for any time of 00:34 as it got changed to 24:34
const time = new Date(myDate).toLocaleTimeString('en',
{ timeStyle: 'short', hour12: false, timeZone: 'UTC' });
It would seem this is a better solution, at least for me.
new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

Convert JS date time to MySQL datetime

Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
console.log(date);
or even shorter:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Output:
2012-06-22 05:40:06
For more advanced use cases, including controlling the timezone, consider using http://momentjs.com/:
require('moment')().format('YYYY-MM-DD HH:mm:ss');
For a lightweight alternative to momentjs, consider https://github.com/taylorhakes/fecha
require('fecha').format('YYYY-MM-DD HH:mm:ss')
I think the solution can be less clunky by using method toISOString(), it has a wide browser compatibility.
So your expression will be a one-liner:
new Date().toISOString().slice(0, 19).replace('T', ' ');
The generated output:
"2017-06-29 17:54:04"
While JS does possess enough basic tools to do this, it's pretty clunky.
/**
* You first need to create a formatting function to pad numbers to two digits…
**/
function twoDigits(d) {
if(0 <= d && d < 10) return "0" + d.toString();
if(-10 < d && d < 0) return "-0" + (-1*d).toString();
return d.toString();
}
/**
* …and then create the method to output the date string as desired.
* Some people hate using prototypes this way, but if you are going
* to apply this to more than one Date object, having it as a prototype
* makes sense.
**/
Date.prototype.toMysqlFormat = function() {
return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
JS time value for MySQL
var datetime = new Date().toLocaleString();
OR
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
OR
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
you can send this in params its will work.
For arbitrary date string,
// Your default date object
var starttime = new Date();
// Get the iso time (GMT 0 == UTC 0)
var isotime = new Date((new Date(starttime)).toISOString() );
// getTime() is the unix time value, in milliseconds.
// getTimezoneOffset() is UTC time and local time in minutes.
// 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds.
var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
// toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
// .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
// .replace('T', ' ') removes the pad between the date and time.
var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
Or a single line solution,
var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
This solution also works for Node.js when using Timestamp in mysql.
#Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype
new Date().toISOString().slice(0, 10)+" "+new Date().toLocaleTimeString('en-GB');
The easiest correct way to convert JS Date to SQL datetime format that occur to me is this one. It correctly handles timezone offset.
const toSqlDatetime = (inputDate) => {
const date = new Date(inputDate)
const dateWithOffest = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
return dateWithOffest
.toISOString()
.slice(0, 19)
.replace('T', ' ')
}
toSqlDatetime(new Date()) // 2019-08-07 11:58:57
toSqlDatetime(new Date('2016-6-23 1:54:16')) // 2016-06-23 01:54:16
Beware that #Paulo Roberto answer will produce incorrect results at the turn on new day (i can't leave comments). For example:
var d = new Date('2016-6-23 1:54:16'),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); // 2016-06-22 01:54:16
We've got 22 June instead of 23!
The venerable DateJS library has a formatting routine (it overrides ".toString()"). You could also do one yourself pretty easily because the "Date" methods give you all the numbers you need.
The short version:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// MySQL formatted UTC timestamp +30 minutes
let d = new Date()
let mySqlTimestamp = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
).toISOString().slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
UTC time is generally the best option for storing timestamps in MySQL. If you don't have root access, then run set time_zone = '+00:00' at the start of your connection.
Display a timestamp in a specific time zone in MySQL with the method convert_tz.
select convert_tz(now(), 'SYSTEM', 'America/Los_Angeles');
JavaScript timestamps are based on your device's clock and include the time zone. Before sending any timestamps generated from JavaScript, you should convert them to UTC time. JavaScript has a method called toISOString() which formats a JavaScript timestamp to look similar to MySQL timestamp and converts the timestamp to UTC time. The final cleanup takes place with slice and replace.
let timestmap = new Date()
timestmap.toISOString().slice(0, 19).replace('T', ' ')
Long version to show what is happening:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// local timezone provided by user's device
let d = new Date()
console.log("JavaScript timestamp: " + d.toLocaleString())
// add 30 minutes
let add30Minutes = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
)
console.log("Add 30 mins: " + add30Minutes.toLocaleString())
// ISO formatted UTC timestamp
// timezone is always zero UTC offset, as denoted by the suffix "Z"
let isoString = add30Minutes.toISOString()
console.log("ISO formatted UTC timestamp: " + isoString)
// MySQL formatted UTC timestamp: YYYY-MM-DD HH:MM:SS
let mySqlTimestamp = isoString.slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
This is by far the easiest way I can think of
new Date().toISOString().slice(0, 19).replace("T", " ")
Full workaround (to mantain the timezone) using #Gajus answer concept:
var d = new Date(),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); //2018-09-28 16:19:34 --example output
I have given simple JavaScript date format examples please check the bellow code
var data = new Date($.now()); // without jquery remove this $.now()
console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)
var d = new Date,
dformat = [d.getFullYear() ,d.getMonth()+1,
d.getDate()
].join('-')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
console.log(dformat) //2016-6-23 15:54:16
Using momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Example please check https://jsfiddle.net/sjy3vjwm/2/
var _t = new Date();
if you want UTC format simply
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
or
_t.toISOString().slice(0, 19).replace('T', ' ');
and if want in specific timezone then
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
Using toJSON() date function as below:
var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
console.log(sqlDatetime);
Datetime in a different time zone
This uses #Gayus solution using the format outputted from toISOString() but it adjusts the minutes to account for the time zone.
Final format: 2022-03-01 13:32:51
let ts = new Date();
ts.setMinutes(ts.getMinutes() - ts.getTimezoneOffset());
console.log(ts.toISOString().slice(0, 19).replace('T', ' '));
I am surprised that no one mention the Swedish date time format for javascript yet.
the BCP 47 language tag for the Swedish language is sv-SE that you can use for the new Date "locale" parameter.
I am not saying it is a good practice, but it works.
console.log(new Date().toLocaleString([['sv-SE']])) //2022-09-10 17:02:39
A simple solution is send a timestamp to MySQL and let it do the conversion. Javascript uses timestamps in milliseconds whereas MySQL expects them to be in seconds - so a division by 1000 is needed:
// Current date / time as a timestamp:
let jsTimestamp = Date.now();
// **OR** a specific date / time as a timestamp:
jsTimestamp = new Date("2020-11-17 16:34:59").getTime();
// Adding 30 minutes (to answer the second part of the question):
jsTimestamp += 30 * 1000;
// Example query converting Javascript timestamp into a MySQL date
let sql = 'SELECT FROM_UNIXTIME(' + jsTimestamp + ' / 1000) AS mysql_date_time';
I needed a function to return the sql timestamp format in javascript form a selective timezone
<script>
console.log(getTimestamp("Europe/Amsterdam")); // Europe/Amsterdam
console.log(getTimestamp()); // UTC
function getTimestamp(timezone) {
if (timezone) {
var dateObject = new Date().toLocaleString("nl-NL", { // it will parse with the timeZone element, not this one
timeZone: timezone, // timezone eg "Europe/Amsterdam" or "UTC"
month: "2-digit",
day: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
let [dateRaw, timeRaw] = dateObject.split(" ");
let [day, month, year] = dateRaw.split("-");
var timestamp = year + "-" + month + "-" + day + " " + timeRaw;
}else{
// UTC from #Gajus, 95% faster then the above
timestamp = new Date().toISOString().slice(0, 19).replace("T", " ");
}
return timestamp; // YYYY-MM-DD HH:MI:SS
}
</script>
If you are using Date-fns then the functionality can be achived easily using format function.
const format = require("date-fns/format");
const date = new Date();
const formattedDate = format(date, "yyyy-MM-dd HH:mm:ss")
This is the easiest way -
new Date().toISOString().slice(0, 19).replace("T", " ")
I'm using this long time and it's very helpful for me, use as you like
Date.prototype.date=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
}
Date.prototype.time=function() {
return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.dateTime=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.addTime=function(time) {
var time=time.split(":")
var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
}
Date.prototype.addDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
}
Date.prototype.subDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
}
and then just:
new Date().date()
which returns current date in 'MySQL format'
for add time is
new Date().addTime('0:30:0')
which will add 30 minutes.... and so on
Solution built on the basis of other answers, while maintaining the timezone and leading zeros:
var d = new Date;
var date = [
d.getFullYear(),
('00' + d.getMonth() + 1).slice(-2),
('00' + d.getDate() + 1).slice(-2)
].join('-');
var time = [
('00' + d.getHours()).slice(-2),
('00' + d.getMinutes()).slice(-2),
('00' + d.getSeconds()).slice(-2)
].join(':');
var dateTime = date + ' ' + time;
console.log(dateTime) // 2021-01-41 13:06:01
Simple: just Replace the T.
Format that I have from my <input class="form-control" type="datetime-local" is :
"2021-02-10T18:18"
So just replace the T, and it would look like this: "2021-02-10 18:18" SQL will eat that.
Here is my function:
var CreatedTime = document.getElementById("example-datetime-local-input").value;
var newTime = CreatedTime.replace("T", " ");
Reference:
https://www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php#:~:text=Answer%3A%20Use%20the%20JavaScript%20replace,the%20global%20(%20g%20)%20modifier.
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string

Categories

Resources