Javascript format date / time [duplicate] - javascript

This question already has answers here:
Formatting the date time with Javascript
(12 answers)
Closed 8 years ago.
I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm
Can this be done using javascript's Date object?

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.
Please take a look at the following JavaScript libraries:
Luxon: [CDN] | [Source] | [Minified]
Moment.js: [CDN] | [Source] | [Minified]
Datejs: [CDN] | [Source] | [Alpha1.zip (1.6MB)]
Demo
Update: I wrote a one-liner using Moment.js Luxon below.
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/1.26.0/luxon.min.js"></script>
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.1/moment.min.js"></script>

For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.

I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.
function formatDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1, // months are zero indexed
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
minuteFormatted = minute < 10 ? "0" + minute : minute,
morning = hour < 12 ? "am" : "pm";
return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
minuteFormatted + morning;
}

You can do that:
function formatAMPM(date) { // This is to display 12 hour format like you asked
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 strTime;
}
var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);
Fiddle

Related

How to convert strings of the format "6 Dec, 2022 " to a date? [duplicate]

In BIRT, i have a column containing a datetime stored as a string. I need to convert these string to datetime format and put the result in another column using Javascript.
The string is the form of: for example: Fri 21 Feb 2014, 09:40 AM.
Hence this when converted to a datetime format and exported to excel, the column should be treat as a date.
Can any one of you help me to do it?
Cheers,
Other answers do not take into consideration this question is in a BIRT context.
Create a computed column in your dataset, with "Date time" as datatype
Enter as expression:
new Date(row["myDateStringField"]);
Where "myDateStringField" is your DateTime column in a String format. Then use this computed column in your report instead of the String column.
That's it!
Checkout momentjs!
You can parse your time of any format like
moment("12-25-1995", "MM-DD-YYYY");
In your case, you don't even have to specify the format. It automatically recognizes it.
And you can output ISO format or convert it to a Javascript Date object.
This is extremely easy to do with javascript. The following code will make a date in a format that Excel will recognize as a date.
http://jsfiddle.net/bbankes/d7SwQ/
var dateString = 'Fri 21 Feb 2014, 09:40 AM';
var date = new Date(dateString);
var yr = date.getFullYear();
var mo = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var hr = hours < 10 ? '0' + hours : hours;
var minutes = date.getMinutes();
var min = (minutes < 10) ? '0' + minutes : minutes;
var seconds = date.getSeconds();
var sec = (seconds < 10) ? '0' + seconds : seconds;
var newDateString = yr + '-' + mo + '-' + day;
var newTimeString = hr + ':' + min + ':' + sec;
var excelDateString = newDateString + ' ' + newTimeString;
If you just want to reformat 'Fri 21 Feb 2014, 09:04 AM' as '2014-02-21 09:04', then the following will do:
function stringToTimestamp(s) {
var t = s.match(/[\d\w]+/g);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
function pad(n){return (n<10?'0':'') + +n;}
var hrs = t[4] % 12;
hrs += /pm$/i.test(t[6])? 12 : 0;
return t[3] + '-' + months[t[2].toLowerCase()] + '-' + pad(t[1]) + ' ' +
pad(hrs) + ':' + pad(t[5]);
}
console.log(stringToTimestamp('Fri 21 Feb 2014, 09:04 AM')); // 2014-02-21 09:04
use the ISO format: YYYY-MM-DDTHH:MM:SS or YYYY-MM-DD
new Date('2011-04-11T11:51:00');
or
new Date('2011-04-11');

How to get +15 minutes date time in Javascript with dd/mm/yyyy hh:ii AM/PM format? [duplicate]

This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 2 years ago.
I have to get +15 minutes date time in Javascript with dd/mm/yyyy hh:ii AM/PM format.
And I should compare two dates, which are in dd/mm/yyyy hh:ii AM/PM format.
JS:
var date = new 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'
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
var dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
var mm = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
var strTime = dd + '/' + mm + '/' + date.getFullYear() + " " + hours + ':' + minutes + ' ' + ampm;
let me first note that by default javascript would be giving you the time in UTC.
A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time are the same as the UNIX epoch, which is the predominant base value for computer-recorded date and time values. (refer)
The above is true when you use the Date() function to create a Date Object
Using ES20xx, you can use a template literal (not supported in IE) and the padStart(not supported in IE) string extension to format the Date object to your liking as shown in the snippet below.
I have also date.toLocaleString() which gives the string in a format that is commonly used in the region from where the browser is running the function
The toLocaleString() method returns a string with a language sensitive
representation of this date. The new locales and options arguments let
applications specify the language whose formatting conventions should
be used and customize the behavior of the function. In older
implementations, which ignore the locales and options arguments, the
locale used and the form of the string returned are entirely
implementation dependent.(refer)
So the easy way to do this would be to add 15 minutes to the Unix timestamp obtained from the Date Object and formatting it with toLocaleString(this is the first snippet)
You can also compare the two date objects below as you would any integer
var dt1 = (new Date()).getTime();//Unix timestamp (in milliseconds)
console.log("Current date Unix timestamp(ms)")
console.log(dt1)
console.log("15 mins later date Unix timestamp(ms)")
console.log(dt1+900000)//15min=900000ms (15*60*1000)
var dt = new Date(dt1);
var dt2= new Date(dt1+900000)
console.log("Unformatted dates 15 min apart (ISO 8601 / UTC)")
console.log(dt)
console.log(dt2)
console.log("Formatted dates 15 min apart (According to your timezone)")
console.log(dt.toLocaleString())
console.log(dt2.toLocaleString())
Below is the longer snippet that involves formatting the date object while displaying it. I feel this is not as optimal as the method above. But still does the job.
var dt = new Date();
console.log(dt);
const localdte = dt.toLocaleString();
console.log(localdte);
const [dated, time, ampm] = localdte.split(' ');
const [hh, mm, ss] = time.split(':');
var date = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
dt.getHours().toString().padStart(2, '0')}:${
dt.getMinutes().toString().padStart(2, '0')}`
console.log("Date right now");
console.log(date);
console.log("date 15 mins later");
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?(dt.hours==23?00:dt.getHours()+1):dt.getHours()).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("24 hour format " + date15);
if (ampm == "PM" && hh != 12 && hh!=00) {
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?(dt.getHours()+1)%12:dt.getHours()%12).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("12 hour format " + date15 + ampm); //12 hour format
} else if (hh == 00) {
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?1:12).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("12 hour format " + date15 + ampm);
} else {
console.log("12 hour format " + date15 + ampm); //12 hour format
}
const dateISO = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), ((dt.getMinutes() + 15) % 60), dt.getMilliseconds());
console.log("ISO 8601 format (UTC)");
console.log(dateISO);
Note: there is a difference in the chrome console and the snippet console outputs. In the chrome console the output the date object is always formatted for local time. In the snippet console, the output of the date object is in UTC and ISO8601 compliant.
Thanks to #RobG for pointing out the errors in my previous answer.

Datetime format conversion in javascript

How to change this 27 June 2018 - 05:25 into Y-m-d H:i:s format?
I don't know how and I'm just a beginner in javascript, can someone help me?
Using moment.js you can parse and format:
var dateStr = moment('27 June 2018 - 05:25', 'DD MMM YYYY - HH:mm').format('YYYY-MM-DD HH:mm:ss');
console.log(dateStr);
Here's a Fiddle: https://jsfiddle.net/z7jz5y8t/1/
You can set custom format like this
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.getFullYear() + "-"+ (date.getMonth()+1) + "-" + date.getDate() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
Also possible duplicate of this 'Javascript format date / time'

JavaScript DateTime not working

function formatDate(dt) {
//var date = new Date(dt);
var date = new Date('2015-08-27 16:00:00'); alert(date.getMonth());
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
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 + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + date.getMonth() + " " + date.getFullYear() + " " + strTime;
}
I have tried to fetch Date and time. But I am getting NaN while alert date.getMonth();.
If I am removing time then this is working fine. But My date-time format dynamic. This is coming from the database like 0000-00-00 00:00:00.
I want to view my database date and time in the 27 Aug 2015 04:00:00 am/pm format.
The date format you are using (2015-08-27 16:00:00) is not the proper format for Firefox, though it works in Chrome. So, for this code to work properly on all browsers, it should not be used.
The below code works in Firefox and Chrome:
I've replaced the string variable date - with /. This format works for both Firefox and Chrome.
Another format that works in Firefox and Chrome is 1995-12-17T03:24:00 which includes T instead of ' ' (space).
However, the above format gives different value in Chrome and Firefox.
new Date('2015-10-05T03:24:00'); // Returns Mon Oct 05 2015 08:54:00 GMT+0530 (IST) in Chrome
new Date('2015-10-05T03:24:00'); // Returns 2015-10-04T21:54:00.000Z in Firefox
var date1 = '2015-08-20 09:38:20';
var date1Updated = new Date(date1.replace(/-/g,'/'));
alert(date1Updated.getMonth());
var strDate = addZero(d.getDate()) + "/" + addZero((d.getMonth() + 1))+"/" +d.getFullYear();
alert("strDate :"+strDate)
return strDate;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
The getMonth() method returns the month (from 0 to 11) for the specified date, according to local time.
Note: January is 0, February is 1, and so on.
you need to add one like getMonth() + 1.
function formatDate(dt) {
//var date = new Date(dt);
var date = new Date('2015-08-27 16:00:00');
//alert(date.getMonth() + 1);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
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 + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + (date.getMonth() + 1) + " " + date.getFullYear() + " " + strTime;
}
alert(formatDate());
In firefox '2015-08-27 16:00:00' is an invalid date.
Your options are
var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);
In your case you're missing the T before the time
Documentation
You have an invalid date format, It seems Chrome handle this situation but firefox not.
new Date('2015-08-27 16:00:00') // Invalid format
new Date('2015-08-27T16:00:00') // Correct Format With T
Your code doesn't work in firefox
In firefox 2015-08-27 16:00:00isn't valid.
To be valid it has to be 2015-08-27T16:00:00.
To make it valid in firefox, the easiest solution would be
function formatDate(dt) {
//var date = new Date(dt);
var sampleDate = "2015-08-27 16:00:00"; // Your sample date as string
var another = sampleDate.replace(' ', 'T');// Change here. Replaced the empty space with the 'T' to make it work in firefox
var date = new Date(another); alert(date.getMonth()); // Using your date to create new Date object
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
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 + ':' + seconds + ' ' + ampm;
return date.getDate() + " " + date.getMonth() + " " + date.getFullYear() + " " + strTime;
}
Hope i was helpfull
Parsing strings using the Date constructor is largely implementation dependent. Only one format of string is specified as being supported by the specification and that changed to some extent between ES5 and ECMAScript 2015.
Your best option is to manually parse the string, either using your own function or a library. The following will suit if the string is consistently the format in the OP and the timezone is UTC:
/* parse dates of format yyyy-mm-dd hh:mm:ss
** e.g. 2015-08-27 16:00:00
**
** #param {string} s - Date string in format yyyy-mm-dd hh:mm:ss
** #returns {Date} - String as Date assuming UTC
**
** Does not validate that the string is valid date or time
**/
function parseDate (s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
document.write(parseDate('2015-08-27 16:00:00'));

How to format a dateTime

Okay I have the following problem. I want to get the current dateTime and then want do check if a date that I enter is bigger than the current DateTime. The format of my dateTime should look like this.
03/11/2012 09:37 AM
Here is the function how I get the current DateTime.
function getCurrentDateTime()
{
var currentTime = new Date()
// Date
var month = currentTime.getMonth() + 1;
if (month < 10){
month = "0" + month;
}
var day = currentTime.getDate();
var year = currentTime.getFullYear();
// Time
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10){
minutes = "0" + minutes;
}
if(hours > 11){
var dateString = month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + "PM";
test = new Date(dateString);
return dateString ;
} else {
var dateString = month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + "AM";
return dateString;
}
}
As you can see how it gives back a string. But when I want to covert it to a date with this function. I get this format Fri May 11 2012 09:37:00 GMT+0200 (Romance Daylight Time)
date = new Date(dateString);
And with this I can't calculate.
Could anybody help me how I can get the current date in this format so that I can do the check?
Kind regards.
Javascript provides very limited functionality for working with dates out of the box. Use an external library like momentjs.
For example, your function would be reduced to
var stringDate = moment().format("DD/MM/YYYY HH:mm A");
And you could convert that and compare it to the current time with
var earlierDate = moment(stringDate, "DD/MM/YYYY HH:mm A");
if (earlierDate.valueOf() < moment().valueOf()) {
// earlier indeed
}
datejs is another lib for solving date-manipulation problems

Categories

Resources