javascript how to change date now format [duplicate] - javascript

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

Related

How to switch seconds to a specific time zone?

I receive the variable, which is seconds. The following code I could switch seconds to date and time. The time zone is Europe where I'm now, but I have to switch it to Asian time zone. I tried add toLocaleString() behind new Date(secOfCookie * 1000), it didn't work. Could anyone give me some help? Thanks!
.toLocaleString("en-US", {
timeZone: "Asia/Tokyo",
timeZoneName: "long",
});
function getTimeSwitchTokyoTime(secOfCookie) {
let date = new Date(secOfCookie * 1000)
let hours = date.getHours()
let minutes = "0" + date.getMinutes();
let seconds = "0" + date.getSeconds();
let formattedTime = date + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
return formattedTime
}
getTimeSwitchTokyoTime(1665224574)
//'Sat Oct 08 2022 12:22:54 GMT+0200 (Central European Summer Time)12:22:54'
I found the way, actually I thought it too complicated..
It's actually easy.
Date(millisecond) could directly switch millisecond to date, and which base on the timezone where I am.
Then I use toLocaleString() to switch to the timezone I want.
new Date(secOfCookie * 1000).toLocaleString(
"en-US",
{
timeZone: "Asia/Tokyo",
timeZoneName: "long",
})
``

Issue parsing dates on devices running iOS and MacOS (apple) operating systems

I have a web application that deals with different time zones. This app stores all the dates in UTC + 00:00 and converts the time to local time right before displaying it using a set of functions I wrote.
It all works well from converting the date string to a datetime object, converting the datetime object from UTC +00:00 to local time, but after I obtain the local datetime string
using date.toLocaleString(), I cannot format it as I want because it returns the following format: 3/23/2021, 9:19:00 PM, and literally all apple devices I tried cannot parse this string and convert it to a valid date.
I simply want to get the local time and format it from 3/23/2021, 9:19:00 PM to 23 Mar 2021 21:19. I have written a function that does this formatting for me but the browser cannot parse 3/23/2021, 9:19:00 PM from a string and convert it to a date object.
I am developing the application in React JS (JavaScript).
Here is the function that does the string parsing and date formatting:
const formatDateString = date => {
const parsed = new Date(Date.parse(date.replace(",", "")))
const months_string = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
const months_array = months_string.split(" ")
let output = ""
output = output + parsed.getDate() < 10 ? "0" + parsed.getDate() : parsed.getDate()
output = output + " " + months_array[parsed.getMonth()]
output = output + " " + parsed.getFullYear()
let hours = parsed.getHours() < 10 ? "0" + parsed.getHours() : parsed.getHours()
output = output + " " + hours
let minutes = parsed.getMinutes() < 10 ? "0" + parsed.getMinutes() : parsed.getMinutes()
output = output + ":" + minutes
return output
}
Your question states that your code "works well from converting the date string to a datetime object ..."
Would this work for you?
let d = new Date();
var options = { year: 'numeric', month: 'short', day: 'numeric' };
var s = d.toLocaleString('en-GB', options);
options = { hour: 'numeric', minute: 'numeric' };
s += ' ' + d.toLocaleString('en-GB', options);
console.log(s);
// output:
// 24 Mar 2021 10:26
Note: using 'en-GB' puts the date in "Day Month Year" order.
I ended up avoiding the parsing problem altogether and creating my own parser that will work for MY scenario. This solution only applies if your input format is same as mine, although it can be modified to work with virtually any date format. Here is the code:
export const formatDateStringApple = date_string => {
const months_string = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
const months_array = months_string.split(" ")
const split_datetime = date_string.split(" ")
const date = split_datetime[0].replace(",", "")
const _split_time = split_datetime[1].split(" ")
const time = _split_time[0]
const isPm = _split_time[1] == "PM" ? true : false
const split_date = date.split("/")
const split_time = time.split(":")
return `${split_date[1]} ${months_array[split_date[0] - 1]} ${split_date[2]} ${isPm ? split_time[0] + 12 : split_time[0] < 10 ? "0" + split_time[0] : split_time[0]}:${split_time[1]}`
}
Maybe (probably) there is a better way of doing this, but this is the quickest one I could come up with.

how to get this specific datetime format in 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

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 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)'.

Categories

Resources