You can build it manually:
var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();
and to force two digits on the values that require it, you can use something like this:
("0000" + 5).slice(-2)
Which would look like this:
var m = new Date();
var dateString =
m.getUTCFullYear() + "/" +
("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
("0" + m.getUTCDate()).slice(-2) + " " +
("0" + m.getUTCHours()).slice(-2) + ":" +
("0" + m.getUTCMinutes()).slice(-2) + ":" +
("0" + m.getUTCSeconds()).slice(-2);
console.log(dateString);
Answer from Joseph Marikle on Stack OverflowVideos
You can build it manually:
var m = new Date();
var dateString = m.getUTCFullYear() +"/"+ (m.getUTCMonth()+1) +"/"+ m.getUTCDate() + " " + m.getUTCHours() + ":" + m.getUTCMinutes() + ":" + m.getUTCSeconds();
and to force two digits on the values that require it, you can use something like this:
("0000" + 5).slice(-2)
Which would look like this:
var m = new Date();
var dateString =
m.getUTCFullYear() + "/" +
("0" + (m.getUTCMonth()+1)).slice(-2) + "/" +
("0" + m.getUTCDate()).slice(-2) + " " +
("0" + m.getUTCHours()).slice(-2) + ":" +
("0" + m.getUTCMinutes()).slice(-2) + ":" +
("0" + m.getUTCSeconds()).slice(-2);
console.log(dateString);
No library, one line, properly padded
const str = (new Date()).toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
It uses the built-in function Date.toISOString(), chops off the ms, replaces the hyphens with slashes, and replaces the T with a space to go from say '2019-01-05T09:01:07.123' to '2019/01/05 09:01:07'.
Local time instead of UTC
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
const dateLocal = new Date(now.getTime() - offsetMs);
const str = dateLocal.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ");
You may want to try
var d = new Date();
d.toLocaleString(); // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString(); // -> "2/1/2013"
d.toLocaleTimeString(); // -> "7:38:05 AM"
Documentation
A JavaScript Date has several methods allowing you to extract its parts:
getFullYear() - Returns the 4-digit year
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.
There are no built-in methods allowing you to get localized strings like "Friday", "February", or "PM". You have to code that yourself. To get the string you want, you at least need to store string representations of days and months:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
Then, put it together using the methods above:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var d = new Date();
var day = days[d.getDay()];
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
hr -= 12;
ampm = "pm";
}
var date = d.getDate();
var month = months[d.getMonth()];
var year = d.getFullYear();
var x = document.getElementById("time");
x.innerHTML = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
<span id="time"></span>
I have a date format function I like to include in my standard library. It takes a format string parameter that defines the desired output. The format strings are loosely based on .Net custom Date and Time format strings. For the format you specified the following format string would work: "dddd h:mmtt d MMM yyyy".
var d = new Date();
var x = document.getElementById("time");
x.innerHTML = formatDate(d, "dddd h:mmtt d MMM yyyy");
Demo: jsfiddle.net/BNkkB/1
Here is my full date formatting function:
const MMMM = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const MMM = MMMM.map(m => m.slice(0, 3));
const dddd = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const ddd = dddd.map(d => d.slice(0, 3));
function ii(i, len = 2) {
return (i + "").padStart(len, "0");
}
function tzHHMM(tz) {
const sign = tz > 0 ? "-" : "+"; // +08:00 == -480, signs are reversed
const tzv = Math.abs(tz);
const tzHrs = Math.floor(tzv / 60);
const tzMin = tzv % 60;
return sign + ii(tzHrs) + ":" + ii(tzMin);
}
function formatDate(date, format, utc) {
const y = utc ? date.getUTCFullYear() : date.getFullYear();
const M = utc ? date.getUTCMonth() : date.getMonth();
const d = utc ? date.getUTCDate() : date.getDate();
const H = utc ? date.getUTCHours() : date.getHours();
const h = H > 12 ? H - 12 : H == 0 ? 12 : H;
const m = utc ? date.getUTCMinutes() : date.getMinutes();
const s = utc ? date.getUTCSeconds() : date.getSeconds();
const f = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
const TT = H < 12 ? "AM" : "PM";
const tt = TT.toLowerCase();
const day = utc ? date.getUTCDay() : date.getDay();
const replacements = {
y,
yy: y.toString().slice(-2),
yyy: y,
yyyy: y,
M,
MM: ii(M),
MMM: MMM[M],
MMMM: MMMM[M],
d,
dd: ii(d),
ddd: ddd[day],
dddd: dddd[day],
H,
HH: ii(H),
h,
hh: ii(h),
m,
mm: ii(m),
s,
ss: ii(s),
f: Math.round(f / 100),
ff: ii(Math.round(f / 10)),
fff: ii(f, 3),
ffff: ii(f * 10, 4),
T: TT[0],
TT,
t: tt[0],
tt,
K: utc ? "Z" : tzHHMM(date.getTimezoneOffset()),
"\\": "",
};
return format.replace(/(?:\\(?=.)|(?<!\\)(?:([yMdf])\1{0,3}|([HhmsTt])\2?|K))/g, $0 => replacements[$0]);
}
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/
Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.
Recommended
The following libraries are recommended for new projects.
Luxon (timezones, successor to Moment)
Luxon is the successor to the Moment.js library. It has native time zone and Intl support.
const { DateTime } = luxon;
const value = DateTime
.fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.toFormat('MM/dd/yyyy h:mm a');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.3.0/luxon.min.js"></script>
js-joda (fixes the Date object)
This is a port of the Joda-Time library in Java. Joda-Time became the java.time package in the Java JDK in version 1.8. It is the successor to the Date object and improves it significantly.
const { DateTimeFormat, DateTimeFormatter, LocalDateTime } = JSJoda;
const { Locale } = JSJodaLocale;
const value = LocalDateTime
.parse('2014-08-20 15:30:00',
DateTimeFormatter.ofPattern('yyyy-M-d HH:mm:ss'))
.format(DateTimeFormatter.ofPattern('MM/dd/yyyy h:mm a')
.withLocale(Locale.US));
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js-joda.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@js-joda/[email protected]/dist/index.min.js"></script>
date-fns (fast, tree-shaking, server-side)
This is version 1.x, if you are using Node.js or another server-side JavaScript engine, you should use version 2.x.
const value = dateFns.format(
dateFns.parse("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss"),
'MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
Day.js (smallest footprint)
A minimalist date library with plugins.
const value = dayjs("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/customParseFormat.min.js"></script>
date-and-time (small footprint)
A minimalist date library with plugins.
const value = date.format(
date.parse("2014-08-20 15:30:00", "YYYY-MM-DD HH:mm:ss"),
'MM/DD/YYYY h:mm A');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdn.jsdelivr.net/npm/[email protected]/date-and-time.min.js"></script>
Not recommended
The following libraries are not recommended for new projects, because they are either no longer supported or do not follow best practices.
Moment (timezones, legacy)
Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.
const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Date.js (small footprint, archived)
This library manipulates the Date prototype. This is not considered best practice.
const value = Date.parse('2014-08-20 15:30:00').toString('MM/dd/yyyy hh:mm tt');
console.log(value); // 08/20/2014 03:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
Without a library
Now, if you really don't want to use a library, a simple tokenizer can assist you in parsing and formatting.
const TOKENS = new Set(['Y', 'M', 'D', 'H', 'h', 'm', 's', 'a']);
const main = () => {
const value = format(parse('2014-08-20 15:30:00', 'YYYY-MM-DD HH:mm:ss'), 'MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
};
const parse = (input, pattern) =>
(tokens => new Date(
+tokens['Y'] , +tokens['M'] - 1 , +tokens['D'],
+tokens['H'] , +tokens['m'] , +tokens['s']
))(tokenize(input, pattern));
const format = (date, pattern) =>
pattern.replace(/\b(\w)(\1)*\b/g, (match) => {
switch (match[0]) {
case 'Y': return date.getFullYear();
case 'M': return `${date.getMonth() + 1}`.padStart(match.length, '0');
case 'D': return `${date.getDate()}`.padStart(match.length, '0');
case 'h': return `${date.getHours() % 12}`.padStart(match.length, '0');
case 'm': return `${date.getMinutes()}`.padStart(match.length, '0');
case 'a': return date.getHours() < 12 ? 'am' : 'pm';
}
return capture;
});
const tokenize = (input, pattern) =>
pattern.split('').reduce((acc, token, index) => TOKENS.has(token)
? { ...acc, [token]: (acc[token] ?? '') + input[index] }
: acc, {});
main();