Handling date strings with various length - javascript

I'm trying to convert dates with different formats to a unified format.
The data I get can be MM/DD/YYYY or M/DD/YYYY or MM/D/YYYY or M/D/YYYY.
As of now I can handle all except M/D/YYYY.
Does anyone know how to solve that?
EDIT: Realized I didn't clarify which format I try to get, it's DD/MM/YYYY
My code as it is (not sure if it's the most efficient way):
var str = "2/13/2016"; // MM/DD/YYYY
var day = str.substr(3,2);
var month = str.substr(0,2);
var year = str.substr(6,4);
if(month.indexOf('/') > -1){
month = month.replace('/','');
var newM = '0' + month;
day = str_date.substr(2,2);
return day + '-' + newM + '-' + year;
}
else if(day.indexOf('/') > -1){
day = day.replace('/','');
var newD = '0' + day;
year = str.substr(5,5);
return newD + '-' + month + '-' + year;
}
else {
return day + '-' + month + '-' + year;
}

Using toLocaleDateString() with en-GB locale
console.log(new Date("2/13/2016").toLocaleDateString('en-GB', {
year: 'numeric', month: '2-digit', day: '2-digit'
}))

One approach would be to split the input string by / into three substring parts, and then parse each part to a number via Number.parseInt(). The final step would be to format a result string based on the three parsed numbers.
In code that could look like this:
var dateA = "2/13/2016"; // MM/DD/YYYY
function parseDate(str) {
const parts = str.split('/').map(part => Number.parseInt(part));
const [month, day, year] = parts;
return `${day}-${month}-${year}`
}
/* M/D/YYYY case */
console.log(parseDate("2/3/2016"), "should equal 3-2-2016");
/* M/DD/YYYY case */
console.log(parseDate("2/03/2016"), "should equal 3-2-2016");
/* MM/D/YYYY case */
console.log(parseDate("02/3/2016"), "should equal 3-2-2016");
/* MM/DD/YYYY case */
console.log(parseDate("02/03/2016"), "should equal 3-2-2016");

You could use momentjs and it's ability to parse a date string in one of several possible formats and format the parsed date in to a specific format.
const dates = ['1/8/2019', '01/8/2019', '1/08/2019', '01/08/2019'],
dateFormats = ['M/D/YYYY', 'MM/D/YYYY', 'M/DD/YYYY', 'MM/DD/YYYY'];
const parsedDates = dates.map((s) =>
moment(s, dateFormats).format('DD-MM-YYYY')
);
console.log(parsedDates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js" integrity="sha256-H9jAz//QLkDOy/nzE9G4aYijQtkLt9FvGmdUTwBk6gs=" crossorigin="anonymous"></script>

look use this code
const arr="2/13/2016".split('/').map(ele=>parseInt(ele))
const [day,mounth,year]=arr;
then check the condition date is the less then 30 and mutch then or equal 1 for day
then check the condition date is the less then 12and mutch then or equal 1for munth
then check the condition date is the less then new Date().getFullYear() mutch then or equal and more then 1950 then this correct date
then const dateWant=${day}/${mounth}/${year};

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));

How to convert current time to EST to ISO 8601 string format? [duplicate]

how do I format a javascript date like ISO format, but in local time?
with myDate.toISOString() I am getting the time as: "2012-09-13T19:12:23.826Z"
but here, it is 22:13, so how do I include the timezone in above format?
I ended up doing...
pad=function(e,t,n){n=n||"0",t=t||2;while((""+e).length<t)e=n+e;return e}
c = new Date()
c.getFullYear()+"-"+pad(c.getMonth()+1)+"-"+pad(c.getDate()-5)+"T"+c.toLocaleTimeString().replace(/\D/g,':')+"."+pad(c.getMilliseconds(),3)
No library required! For some Date object, e.g. t = new Date()
convert the local time zone offset from minutes to milliseconds
z = t.getTimezoneOffset() * 60 * 1000
subtract the offset from t
tLocal = t-z
create shifted Date object
tLocal = new Date(tLocal)
convert to ISO format string
iso = tLocal.toISOString()
drop the milliseconds and zone
iso = iso.split(".")[0]
replace the ugly 'T' with a space
iso = iso.replace('T', ' ')
Result is a nice ISO-ish format date-time string like "2018-08-01 22:45:50" in the local time zone.
A bit of a hack but can be done in one line by taking advantage of the fact that Sweden uses a format very close to ISO:
// Returns a string like 2021-01-17T01:59:57
function dateToISOButLocal(date) {
return date.toLocaleString('sv').replace(' ', 'T');
}
To support milliseconds:
return date.toLocaleString('sv', {year:'numeric', month:'numeric', day:'numeric', hour:'numeric', minute:'numeric', second:'numeric', fractionalSecondDigits: 3}).replace(',', '.').replace(' ', 'T');
I went with what Denis Howe said, below as a ready made function for convenience.
Also one fix: in the original answer t-z does not work because t is a Date, not milliseconds.
function dateToISOLikeButLocal(date) {
const offsetMs = date.getTimezoneOffset() * 60 * 1000;
const msLocal = date.getTime() - offsetMs;
const dateLocal = new Date(msLocal);
const iso = dateLocal.toISOString();
const isoLocal = iso.slice(0, 19);
return isoLocal;
}
With this I get the kind of string that needed as a URL parameter:
"2018-11-16T12:23:50"
AFAIK you can't format dates in javascript (without using external libraries). The best you could do is "format it yourself". I mean:
var date = new Date();
var year = date.getFullYear();
var month = date......
var ISOdate = year + "-" + month + "-" + .... ;
But there are some good libraries that will let you format dates! (read "format" as in library.getDate("YYYY-MM-DD.........");)
EDIT:
Moment.js seems the thing you're looking for: http://momentjs.com/
Although answers here might work, there's nothing like a simple one-liner:
new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toISOString()
Explanation for those who are interested:
We create a new instance of Date (the outer one).
We give it another instance of Date (in milliseconds) from which we subtract the timezone offset (in milliseconds too, either positive or negative). All of this we format into ISO
I don't quite understand which date did you need
but I think you need
const ISOLocaleString = d => {
const pad = n => n < 10 ? '0'+n : n;
return d.getFullYear()+'-'
+ pad(d.getMonth()+1)+'-'
+ pad(d.getDate())+'T'
+ pad(d.getHours())+':'
+ pad(d.getMinutes())+':'
+ pad(d.getSeconds())+'Z'
}
or
const ISOUTCLocaleString = d => {
const pad = n => n<10 ? '0'+n : n;
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
In the original post, the current ISO date is "2012-09-13T19:12:23.826Z"
If what is wanted is a date that respects ISO norm but reflects the local offset from UTC time, the target answer should be "2012-09-13T22:12:23.826+03:00".
Best answer in the post bellow, with code snippet that respects the ISO 8601 format / RFC 3339
https://stackoverflow.com/a/17415677/1563072
Another method is to define a prototype on the Date object that leverages the built-in toISOString method (a separate function is also provided):
// Extend Date.prototype
Date.prototype.toLocalISOString = function() {
// Get the local offset for the date in minutes
let offsetMins = this.getTimezoneOffset();
// Get a time value adjusted for the offset
let localTimeMs = this - offsetMins * 6e4;
// Make a new Date so don't affect this
let date = new Date(localTimeMs);
// Get the local offset sign (ECMAScript sign is opposite to usual)
let utcOffsetSign = offsetMins > 0? '-' : '+';
// Remove sign from offsetMins
offsetMins = Math.abs(offsetMins);
// Get offset hours and minutes, padd to 2 digits
let utcOffsetHr = String(offsetMins / 60 | 0).padStart(2,'0');
let utcOffsetMin = String(offsetMins % 60).padStart(2,'0');
// Build offset string
let utcOffsetString = `${utcOffsetSign}${utcOffsetHr}:${utcOffsetMin}`;
// Return as adjusted ISO 8601 format string with adjusted offset
return date.toISOString().replace('Z', utcOffsetString);
};
// E.g.
let date = new Date();
// Like 2020-08-04T14:52:38.613-07:00
console.log(`UTC : ${date.toISOString()}\n` +
`Local: ${date.toLocalISOString()}`);
// Stand alone function
function toISOLocal(date) {
let offsetMins = date.getTimezoneOffset();
let d = new Date(date - offsetMins*6e4);
let offsetSign = offsetMins > 0? '-' : '+';
offsetMins = Math.abs(offsetMins);
let offsetHr = String(offsetMins / 60 | 0).padStart(2,'0');
let offsetMin = String(offsetMins % 60).padStart(2,'0');
return d.toISOString().replace('Z', `${offsetSign}${offsetHr}:${offsetMin}`);
}
// Like 2020-08-04T14:52:38.613-07:00
console.log(`fn : ${toISOLocal(date)}`);
ISO 8601 is simply a way of formatting dates and can as such can be applied to any time zone.
Have you tried the timeZone option to the Date object's toLocaleString method?
This question has answers with examples.
This is the method I use. It takes care to add zeros if date/month/hour etc is single digit number (for example turns '6' to '06')
function formatLikeISO (d: Date): string {
let lengthChecker = (str) => {
if (str.length == 1) { return '0' + str; }
return str;
}
let theDate = lengthChecker(String(d.getDate()));
let month = lengthChecker(String(d.getMonth() + 1));
let mins = lengthChecker(String(d.getMinutes()));
let hours = lengthChecker(String(d.getHours()));
let secs = lengthChecker(String(d.getSeconds()));
let formatted =
d.getFullYear() + '-' +
month + '-' +
theDate + ' ' +
hours + ':' +
mins + ':' +
secs;
return formatted;
}
This will output this kind of format:
"2021-06-30 11:31:34"
There's no direct way to do this. However, you can use toLocaleString to create a string that you can easily parse to make it an ISO string.
This works on node:
function getLocalIsoTime(time, timezone) {
const local = time.toLocaleString("en-US", {timeZone: timezone, hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit"});
return `${local.substr(6, 4)}-${local.substr(0, 2)}-${local.substr(3, 2)}T${local.substr(12, 8)}`;
}
console.log(getLocalIsoTime(new Date(), 'Asia/Kolkata'));
A simpler version works on node 15+ and on most modern browsers:
function getLocalIsoTime(time, timezone) {
return time.toLocaleString("en-CA", {timeZone: timezone, hour12: false}).replace(/, /, "T");
}
console.log(getLocalIsoTime(new Date(), 'Asia/Kolkata'));
Based on https://stackoverflow.com/a/68191554/833960, but I wanted the ms to be present and consistent width output of 3 digits for ms.
function formatLikeISO(d: Date): string {
let lengthChecker = (str: string, targetLen = 2) => {
if (str.length < targetLen) {
return str.padStart(targetLen, '0')
}
return str
}
let day = lengthChecker(String(d.getDate()))
let month = lengthChecker(String(d.getMonth() + 1))
let mins = lengthChecker(String(d.getMinutes()))
let hours = lengthChecker(String(d.getHours()))
let secs = lengthChecker(String(d.getSeconds()))
let ms = lengthChecker(String(d.getMilliseconds()), 3)
let formatted =
d.getFullYear() +
'-' +
month +
'-' +
day +
' ' +
hours +
':' +
mins +
':' +
secs +
'.' +
ms
return formatted
}
Output:
2023-02-13 10:23:59.025
2023-02-13 10:23:59.026
2023-02-13 10:23:59.026
2023-02-13 10:23:59.030
2023-02-13 10:23:59.438
2023-02-13 10:23:59.438

Remove time part from date in js

let date = invoice.due_date;
console.log(date);
Output 2019-06-13 00:00:00
d = date.split(' ')[0]; //didnt work for me
How can I remove the time and only have the date.
I just added .toLocaleDateString
The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the date. The locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
let date = new Date("2019-06-13T02:00:00Z").toLocaleDateString()
console.log(date)
Reference:
toLocaleDateString
Another Example:
If you want to have a ISO Date try this one:
date = new Date('2019-06-13T02: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);
let date = invoice.due_date;
console.log(date.getDate() + '-' + (date.getMonth()+1) + '-' + date.getFullYear());
You can try this way. Can create any format like dd-MM-yyyy or anything.
Recommendation: Use moment library for date formatting.
If you had a string, the split would work.
It is either not a string (e.g. null) or something else not a string.
Your console.log shows a date string so it is obviously a Date object.
To get the second part in ANY case (space or with a T between the date and time) you need to get the ISOString to be able to PERSISTENTLY get the correct output.
Any toLocaleString or similar is implementation and locale dependent
let date = invoice.due_date.toISOString()
Like this:
// Assuming a date object because your console log and the split that does not work
const invoice = {
due_date : new Date("2019-06-13 00:00:00") // EXAMPLE date
}
let date = invoice.due_date.toISOString();
console.log(date)
console.log(date.split(/[T| ]/)[0]); // take space or "T" as delimiter
You can convert the date string to a Date Object:
let dataObj = new Date(date)
and then format it as given in this link

Jquery Date Format Conversion [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)
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);
}

Convert yyyy-MM-dd to MM/dd/yyyy in javascript

This might be a simple solution but I am stuck, basically I need convert an incoming yyyy-MM-dd to MM/dd/yyyy also, if incoming date is nil, then output should also be nil.
Incoming date could be of following format
2015-01-25 or nil
Output date shoud be
01/25/2015 or nil
I was trying one from the following link
Convert Date yyyy/mm/dd to MM dd yyyy but couldn't make it work.
Thanks for any help.
Forgot to mention, the incoming date which comes as nil is of the following format in an xml file
<Through_Date__c xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
So if I get the above format the output should be just be nil
The date toString function has some support for formatting. See this. And you also want to handle the undefined case which I took from here. So, for your case you can just do this:
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
// Months use 0 index.
return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
}
}
EDIT: Addressing the comment
If the padding is important you just need to add that in:
var d = date.getDate().toString();
(d[1]?d:"0"+d[0])
I've made an update to the fiddle
Try using RegEx:
var format = function(input) {
var pattern = /(\d{4})\-(\d{2})\-(\d{2})/;
if (!input || !input.match(pattern)) {
return null;
}
return input.replace(pattern, '$2/$3/$1');
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
Using String#split and Array#join, push & shift:
var format = function(input) {
var array = (input || '').toString().split(/\-/g);
array.push(array.shift());
return array.join('/') || null;
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
if you wanna go ghetto style and use easily understandable code, and you dont care about using a date object, try this!
function changeDateFormat(inputDate){ // expects Y-m-d
var splitDate = inputDate.split('-');
if(splitDate.count == 0){
return null;
}
var year = splitDate[0];
var month = splitDate[1];
var day = splitDate[2];
return month + '\\' + day + '\\' + year;
}
var inputDate = '2015-01-25';
var newDate = changeDateFormat(inputDate);
console.log(newDate); // 01/25/2015
you can deal your javascript dates in various formats.
For dd/MM/yyyy you can use
var date = new Date().toLocalDateString()
or
var date = new Date('2021-07-28').toLocalDateString()
output: '28/07/2021'
For MM/dd/yyyy
var date = new Date().toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
or
var date = new Date('2021-07-28').toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
output: '07/28/2021'
Alternatively you can handle custom date formats using following date functions
let date = new Date()
let dateString = [
date.getMonth() + 1,
date.getDate(),
date.getFullYear(),
].join('/')
}
output: 07/28/2021
If your date has not yet been parsed from a string, you can simply rearrange its components:
var s = '2015-01-25';
if (s) {
s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, function(match,y,m,d) {
return m + '/' + d + '/' + y;
});
}
Thanks guys, I was able to do grab some ideas from all your posts and came up with this code which seems to working fine in my case
if((typeof inStr == 'undefined') || (inStr == null) ||
(inStr.length <= 0)) {
return '';
}
var year = inStr.substring(0, 4);
var month = inStr.substring(5, 7);
var day = inStr.substring(8, 10);
return month + '/' + day + '/' + year;
You can also try the method below using vanilla JS. I have converted the date to a string & parsed it to get the format you're looking for:
function tranformDate(strDate) {
let result = '';
if (date) {
let parts = date.split('-');
result = `${parts[1]}/${parts[2]}/${parts[0]}`;
}
return result;
}
let date = new Date().toISOString().split('T')[0];
console.log('raw date: ' + date);
console.log('formatted date: ' + tranformDate(date));

Categories

Resources