how to get this specific datetime format in javascript - javascript

In javascript, is there a way to convert a date time to the following format:
// 11/3/18, 12:00 AM
Date().toString() gives me:
Sat Nov 03 2018 00:00:00 GMT+0000 (UTC)
Thanks.

This is an alternative to format dates, the function Date.prototype.toLocaleDateString allows you to format date according to options/flags.
Some js engines manage the format process differently (so, this is implementation dependent), therefore be careful. Further, you need to check for compatibility in browsers.
let today = new Date();
var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour12: true, hour: 'numeric', minute: 'numeric' };
console.log(today.toLocaleDateString('en-US', options));

tl;dr: try typing this in your browser's javascript console on the moment.js website: moment().format('MM/d/YY h:mm A')
Three things:
1. If you haven't already, check out these date docs for the API:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
(Thorough backgrounder): https://www.toptal.com/software/definitive-guide-to-datetime-manipulation
2. Without an external library
See Ele's answer above for most elegant non-library: https://stackoverflow.com/a/53135859/3191929
Ex. Extract mm/dd/yy from Date
const root = new Date();
let month = root.getMonth(); // 0 to 11
let day = root.getDate(); // 1 to 31
let year = root.getFullYear(); year = String(year).slice(2);
// 11/3/18, 12:00 AM mm/dd/yy, hh:mm AM/PM
const output = ``${month}/${day}/${year}``; // mm/dd/yy
And from there you can explore the API to get the 24 hours, then do a check for AM/PM and build the result etc etc. (see bbram's answer here: https://stackoverflow.com/a/8888498/3191929 for the relevant Date APIs for time)
Here's a quick'n'dirty solution to your specific question
Ex. Extract mm/dd/yy hh:mm AM/PM from Date
function formatDate(root) {
let month = root.getMonth(); // 0 to 11, 0 = Jan
month += 1; // 1 to 12, 1 = Jan
let day = root.getDate(); // 1 to 31
let year = root.getFullYear();
year = String(year).slice(2);
// Time transformation appropriated from bbrame
// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format/8888498#8888498
function formatAMPM(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 strTime;
}
// mm/dd/yy, hh:mm AM/PM
const output = `${month}/${day}/${year} ${formatAMPM(root)}`;
return output;
}
var rootDate = new Date();
console.log(formatDate(rootDate)); // mm/dd/yy hh:mm AM/PM
3. With an external library
Using moment.js you can achieve the above with just this:
var root = moment(); // valid moment date
var formatted = root.format('m/d/YY h:mm A');
See the moment.js docs for more details: https://momentjs.com/docs/#/displaying/format/
If momentjs specifically is a no-go, see here for other options as well: https://github.com/you-dont-need/You-Dont-Need-Momentjs

Related

javascript how to change date now format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I am facing an issue with javascript dates. I want to change the format of date
this.setState({
current: Date(Date.now()),
}, 1000);
//convert minutes
//if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00
//if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30
var slotTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ; //10:30
Output:
Thu May 14 2020 10:00:30 GMT+0500 (Pakistan Standard Time)
Expected
10:00:52 AM
10:30 AM
What should I change?
You can simply use Date toLocaleTimeString() method like:
const current = new Date()
const timestring = current.toLocaleTimeString()
console.log( timestring ) //=> 10:47:52 AM
The toLocaleTimeString() method returns a string with a language sensitive representation of the time portion of the date.
To only get hh:mm a format you can pass option object to the toLocaleTimeString() method like:
const current = new Date()
const timestring = current.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
console.log( timestring ) //=> 10:50 AM
With setState:
this.setState({
current: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
});
var date=new Date();
console.log(date.getHours() + ":" + date.getMinutes()+ ":" + date.getSeconds() + " " + date.getHours()<12 ? 'AM' : 'PM'}`);
OUTPUT : 11:9:37 AM
date.getHours()<12 results in AM between 12Am to 11:59 AM and after 11:59 it results in PM

Convert Epoch time to human readable with specific timezone

To convert epoch dateTime to human readable , using a simple new date(1495159447834) will suffice.
The problem I'm encountering now is that for my hybrid application, if the user set the time-zone in his phone date time setting to lets say GMT +12:00 ,the human readable dateTime will be different from what I would want the user to have and I would want him/her to follow the server timezone.
Thus , how would I convert the epoch number to a specific given timezone in a human readable format.
I have tried example like:
var test= new Date('1495159447834 GMT+0800').toString();
and it returns me an Invalid Date.
If possible, I would want this without any libraries. I have looked through the answers here and I believe that I could not find any answers I'm looking for. If there is any previously answered question with the same topic, do let me know and I will close this question!
You can use offset to convert your current datetime to a specific timezone.
function convertEpochToSpecificTimezone(timeEpoch, offset){
var d = new Date(timeEpoch);
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); //This converts to UTC 00:00
var nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
// convertEpochToSpecificTimezone(1495159447834, +3)
The offset will be your specific timezone. Example: GMT +03:00, your offset is +3. If GMT -10:00, offset is -10
there are number of ways to convert between Epoch and Human readable format
//Convert epoch to human readable date
var myDate = new Date( 1533132667*1000);
document.write(myDate.toGMTString()+"<hr>"+myDate.toLocaleString());
//this will return Wed, 01 Aug 2018 14:11:07 GMT
//Convert human readable dates to epoch
var myDate = new Date("Wed Aug 01 2018 14:11:07 GMT");
var myEpoch = myDate.getTime()/1000.0;
// this will return 1533132667
For Reference: https://www.epochconverter.com/programming/#javascript
Edit#
added a JSFiddle here
This is old, but I did it this way:
function formatDate(date, includeTime) {
const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZone: 'America/Los_Angeles',
timeZoneName: 'short',
});
const [
{ value: month },
,
{ value: day },
,
{ value: year },
,
{ value: hour },
,
{ value: minute },
,
{ value: dayPeriod },
,
{ value: timeZoneName },
] = dateTimeFormat.formatToParts(date);
if (includeTime) {
return `${day} ${month} ${year} • ${hour}:${minute}${dayPeriod.toLowerCase()} ${timeZoneName}`;
}
return `${day} ${month} ${year}`;
This will output the time of the given timezone.
For example, if I have an epoch time (unix timestamp) and if I'm in Argentina, the time should be displayed as 03:45 GMT -3 of June 2, but with this code, it will be displayed as the time that should be displayed for Los Angeles.
My requirement was to display time in Los Angeles timezone, even if I visit the page from Argentina.
set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to
the epoch
d.setUTCSeconds(utcSeconds);
Or you can use momentjs
moment.unix(yourUnixEpochTime).format('dddd, MMMM Do, YYYY h:mm:ss A')
or you can use this way
var dateVal ="/Date(1342709595000)/";
var date = new Date(parseFloat(dateVal.substr(6)));
document.write(
(date.getMonth() + 1) + "/" +
date.getDate() + "/" +
date.getFullYear() + " " +
date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds()
);

How to display the current day + 30 days with Javascript?

I try to insert the date of today + 30 days. First of all I tried to display the current date with the following code:
<script>
var date = moment.unix(1414543560).locale('de').format("DD. MMMM YYYY");
document.write(date);
</script>
This displays the right day and Month, but unfortunately the Year is wrong (it's actually 2014)
How can I display the correct date of today + 30 days? Any ideas?
https://jsfiddle.net/e3a7bgLu/3/
Try
var date = moment().add(30, 'days').locale('de').format("DD. MMMM YYYY");
document.write(date);
This takes the current date (moment()), adds 30 days (add(30, 'days')) and formats the date.
This should all be very obvious after you read the moment.js documentation.
function addDate(date,days){
var d=new Date(date);
d.setDate(d.getDate()+days);
var month=d.getMonth()+1;
var day = d.getDate();
if(month<10){
month = "0"+month;
}
if(day<10){
day = "0"+day;
}
var val = d.getFullYear()+"-"+month+"-"+day;
return val;
}
console.log(addDate("2014-10-10",30));
#output
2014-11-09
You can pass a UNIX timestamp to the Date contructor in JavaScript set the date to 30 days in the future and pass that date to Moment.
// Construct date from UNIX timestamp
var date = new Date(1414543560 * 1000)
// Set date to 30 days in the future
date.setDate(date.getDate() + 30)
// Format date using Moment
var formatted = moment(date).locale('de').format('DD. MMMM YYYY')
Note that if your support target allows it you don't even need Moment anymore, you can use the built-in Internationalization API that comes with the browser.
// Construct date from UNIX timestamp
var date = new Date(1414543560 * 1000)
// Set date to 30 days in the future
date.setDate(date.getDate() + 30)
// Format date using Intl API
var formatted = date.toLocaleDateString(['de-DE'], {
day: '2-digit',
month: 'long',
year: 'numeric'
})
document.write(formatted)

How can I convert string formatted UTC dates without offset to local time in JavaScript?

I am getting a string formatted date with UTC timezone. I need to convert this date time in user's current time zone using jquery or javascript.
I am getting this:
9:43pm 16/10/2015 //this is UTC time, I am getting this via an ajax call
I need to convert it to this:
12:00pm 16/10/2015 //whatever time by that location
If you can pick that format apart, or get a standard format JavaScript can parse - you can convert it to a Date object. I'm not seeing an offset on that date which is problematic when JavaScript tries to parse it. Assuming that is all you have, we can force a UTC date with the following...
// ------- new Date(Date.UTC(year, month, day, hour, minute, second))
var date = new Date(Date.UTC(2015, 9, 16, 21, 43, 0));
console.log(date) // Fri Oct 16 2015 15:43:00 GMT-0600 (Mountain Daylight Time (Mexico))
note that month in Date.UTC is zero based e.g. October would be 9
new Date(value) would do this for us automatically if the format is correct - where value is the actual date value you receive - but that format will not parse as is. If there is no way around that format, you can manipulate it to work in the above example. Here is an untested algorithm for your example...
var formatted = '9:43pm 16/10/2015'
function createDateUTC(formatted) {
var hourOffset = formatted.split(' ')[0].split(':')[1].match(/[a-zA-Z]+/g)[0] === 'pm' ? 12 : 0
var year = parseInt(formatted.split('/').pop());
var month = parseInt(formatted.split('/')[1]) - 1;
var day = parseInt(formatted.split('/')[0].split(' ').pop());
var hour = hourOffset + parseInt(formatted.split(' ')[0].split(':')[0]);
var minute = parseInt(formatted.split(' ')[0].split(':')[1]);
return new Date(Date.UTC(year, month, day, hour, minute, 0));
}
var myDate = createDateUTC(formatted);
JSFiddle Link - working demo
Check out the UTC() and Date Object docs for more info
Additionally, to get the exact format you want, we can introduce some more functions which will give us the 12:00pm 16/10/2015 format
function formatAMPM(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 strTime;
}
function formatMMDDYYYY(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
console.log(formatAMPM(myDate) + ' ' + formatMMDDYYYY(myDate));
// Mountain Daylight Time => -- 3:43pm 16/10/2015
JSFiddle Link - formatted example
I'd reccoment looking into Moment.js if you plan to do heavy date formatting and manipulation.
Overall - the best solution to this would be to return an acceptable format from the server, resolve it to local time natively e.g. new Date(), and use a robust formatting library as opposed to rolling your own to display it how you wish.
You should process that string a little bit to extract year, month, day, hour and minute.
Then you can create a local date with that UTC date using this:
var time = new Date ( Date.UTC('year', 'month', 'day', 'hour', 'minute') );
In my case, '9:43pm 16/10/2015' returns: 'Mon Nov 16 2015 07:43:00 GMT-0200 (Hora de verano de Argentina)'.

How can I add 1 day to current date?

I have a current Date object that needs to be incremented by one day using the JavaScript Date object. I have the following code in place:
var ds = stringFormat("{day} {date} {month} {year}", {
day: companyname.i18n.translate("day", language)[date.getUTCDay()],
date: date.getUTCDate(),
month: companyname.i18n.translate("month", language)[date.getUTCMonth()],
year: date.getUTCFullYear()
});
How can I add one day to it?
I've added +1 to getUTCDay() and getUTCDate() but it doesn't display 'Sunday'
for day, which I am expecting to happen.
To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);
In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if you are on the last day of the month.
For example Feb 28 or march 31.
Here is an example of how I would do it:
var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();
Imho this insures accuracy
Here is another example. I do not like that. It can work for you but not as clean as example above.
var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();
Imho this === 'POOP'
So some of you have had gripes about my millisecond approach because of day light savings time. So I'm going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number does not change once a year but then gets fixed 6 months later I don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() I have thought this through and now thoroughly hate Date. So this is my new Approach.
var dd = new Date(); // or any date and time you care about
var dateArray = dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z
Now for the fun part!
var date = {
day: dateArray[2],
month: dateArray[1],
year: dateArray[0],
hour: dateArray[3],
minutes: dateArray[4],
seconds:dateArray[5].split('.')[0],
milliseconds: dateArray[5].split('.')[1].replace('Z','')
}
Now we have our Official Valid international Date Object clearly written out at Zulu meridian.
Now to change the date
dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.
If you want add a day (24 hours) to current datetime you can add milliseconds like this:
new Date(Date.now() + ( 3600 * 1000 * 24))
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
CodePen
var days = 2;
var newDate = new Date(Date.now()+days*24*60*60*1000);
document.write('Today: <em>');
document.write(new Date());
document.write('</em><br/> New: <strong>');
document.write(newDate);
Inspired by jpmottin in this question, here's the one line code:
var dateStr = '2019-01-01';
var days = 1;
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)
document.write('<br />');
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
Hope this helps
simply you can do this
var date = new Date();
date.setDate(date.getDate() + 1);
console.log(date);
now the date will be the date of tomorrow. here you can add or deduct the number of days as you wish.
This is function you can use to add a given day to a current date in javascript.
function addDayToCurrentDate(days){
let currentDate = new Date()
return new Date(currentDate.setDate(currentDate.getDate() + days))
}
// current date = Sun Oct 02 2021 13:07:46 GMT+0200 (South Africa Standard Time)
// days = 2
console.log(addDayToCurrentDate(2))
// Mon Oct 04 2021 13:08:18 GMT+0200 (South Africa Standard Time)
// Function gets date and count days to add to passed date
function addDays(dateTime, count_days = 0){
return new Date(new Date(dateTime).setDate(dateTime.getDate() + count_days));
}
// Create some date
const today = new Date("2022-02-19T00:00:00Z");
// Add some days to date
const tomorrow = addDays(today, 1);
// Result
console.log("Tomorrow => ", new Date(tomorrow).toISOString());
// 2022-02-20T00:00:00.000Z
We can get date of the day after today by using timedelta with numOfDays specified as 1 below.
from datetime import date, timedelta
tomorrow = date.today() + timedelta(days=1)
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

Categories

Resources