Custom Time Format in Excel for Sorting

Abstract: Fixes incorrect alphabetical sorting of time values in Excel by ensuring custom formats preserve the underlying numeric serial number.

Created: 2026-10-24 by

Excel sorts time values as text if the cell format is not recognized as a true time serial number. To ensure custom formats like "hh:mm" or "h:mm:ss" sort chronologically rather than alphabetically, you must preserve the underlying numeric value while changing only the display. This article explains how to apply custom formats that maintain sortability without altering the data source.

Understanding Excel's Internal Time Storage

Before applying any custom formatting, it is crucial to understand how Excel handles time data internally. Excel stores dates and times as serial numbers, where the integer part represents the date and the decimal fraction represents the time of day. For example, noon is stored as 0.5 because it is half of a 24-hour day. When you apply a standard time format, Excel retains this underlying numeric value while changing how it appears on the screen. The problem arises when users attempt to create custom time formats that do not align with Excel's internal logic. If you use a format string that includes text elements or non-standard separators, Excel may treat the content as plain text. Text sorting in Excel follows alphabetical order, meaning "10:00 AM" will appear after "9:00 AM" but before "8:00 AM" only if the leading digit is considered. However, "2:00 PM" will often appear before "10:00 AM" because "2" comes before "1" in some contexts or simply because the string comparison fails to recognize the temporal relationship. Therefore, the goal is to customize the visual representation without breaking the numeric link.

The Danger of Non-Numeric Formats

A common mistake is using formats that include AM/PM indicators alongside hours that exceed 12, or using formats that force a specific string length that conflicts with natural sorting. For instance, a format like "h:mm AM/PM" works well for sorting because Excel still recognizes the underlying value. However, if you manually type text into cells to mimic a time format, Excel cannot sort them correctly. Always verify that your cells contain actual time values by checking the alignment (right-aligned by default) or by using the =ISNUMBER() function. If the result is false, the cell contains text, and sorting will be unreliable.

Setting Up Sortable Custom Time Formats

To create a custom time format that respects sorting, follow these steps to modify the cell appearance while keeping the data intact. This process ensures that your reports look professional while maintaining accurate chronological order during data analysis.
  1. Select the range of cells containing your time data.
  2. Right-click and choose Format Cells, or press Ctrl + 1.
  3. Navigate to the Number tab and select Custom from the category list.
  4. In the Type box, enter your desired format code. Common sortable codes include hh:mm, h:mm:ss, or [h]:mm for durations exceeding 24 hours.
  5. Click OK to apply the format.
The key to success here is using format codes that map directly to the serial number structure. The hh specifier forces two-digit hours, which can help with visual consistency, but it does not change the sort order. The critical factor is avoiding any characters that break the numeric interpretation. For example, adding a literal string like "Time: " at the beginning of the format will convert the cell to text, destroying its sortability.

Handling Durations and Negative Times

If you are working with time durations or negative time intervals, standard formats may fail. Excel cannot natively display negative time values in most standard formats, often showing hashes (######) instead. To handle this, you must use a custom format that explicitly allows for negative signs. Use a format like [h]:mm:ss;-;[h]:mm:ss. The semicolons separate the positive, zero, and negative conditions. This ensures that even if your calculations result in negative time differences, Excel displays them correctly and maintains their numerical value for sorting purposes. For more complex sorting scenarios involving custom lists, such as ordering days of the week or specific project phases alongside time data, refer to our guide on Correctly Sorting an Excel Custom List: A Step-by-Step Guide. This resource details how to integrate custom orderings with standard time columns.

Troubleshooting Sorting Issues

Even with correct formatting, sorting issues can persist due to hidden characters or mixed data types within a column. If your time column refuses to sort chronologically, perform the following diagnostic checks. First, check for leading or trailing spaces. These invisible characters can cause Excel to treat a valid time as text. Use the =TRIM() function to clean the data, or find and replace spaces with nothing. Second, ensure there are no blank cells or error values interspersed with the time data. Blank cells can disrupt the sort algorithm, causing rows to shift unpredictably. Third, verify that the entire dataset is selected when sorting. If you have adjacent columns with different data types, Excel may prompt you to expand the selection. Always choose to expand the selection to keep related data together during the sort operation. If you frequently need to reverse the order of your sorted data, such as viewing the most recent times first, you can quickly toggle between ascending and descending orders. For detailed instructions on managing reverse sorts, see our article on Sort Excel Sheet in Reverse Order: A Step-by-Step Guide.

Advanced Tips for Data Integrity

When dealing with large datasets, consider using Excel Tables (Ctrl + T). Tables automatically apply consistent formatting to new rows added to the dataset. This prevents accidental loss of custom time formats when pasting new data. Additionally, using structured references in formulas ensures that your time calculations remain robust even as the dataset grows. Another best practice is to separate raw data from presentation data. Keep a hidden column with the raw serial number values used for all sorting and filtering operations. Then, create a visible column that applies the custom format for display. This approach guarantees that your sorting logic never breaks, regardless of how you style the output for stakeholders.

Frequently Asked Questions

Why does my time sort alphabetically instead of chronologically?

This occurs because Excel treats the cell content as text rather than a numeric time value. Text sorting relies on character codes, so "10:00" comes after "9:00" only if the first digits are compared correctly, but "2:00" may appear out of order. Ensure your cells are formatted as Time or General, not Text, to restore chronological sorting.

Can I use AM/PM in my custom time format and still sort correctly?

Yes, you can use AM/PM indicators in your custom format code, such as h:mm AM/PM, and the data will still sort correctly. As long as the underlying value remains a serial number, Excel preserves the temporal relationship. Avoid adding static text labels that might confuse the parser.

How do I fix negative time values that show as hashes?

Negative time values display as hashes because standard formats cannot represent them. You must create a custom format that includes a condition for negative numbers, such as [h]:mm:ss;-;[h]:mm:ss. This tells Excel to display the negative sign and the duration properly.

What should I do if my custom format disappears after copying data?

Copying and pasting data often resets cell formatting unless you use Paste Special > Values or Paste Special > Formats. To preserve your custom time format, ensure you are pasting into cells that already have the correct format, or use the Format Painter tool to transfer the styling accurately.

Does sorting affect the actual time values in my spreadsheet?

No, sorting only changes the order of the rows; it does not alter the underlying data values. Whether you sort ascending or descending, the time serial numbers remain identical. Your calculations based on these times will yield the same results regardless of the row position.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More